doubipiao1611 2010-08-15 12:15
浏览 46
已采纳

PHP:by-reference-function,boolean作为返回值 - 奇怪的通知

I have a function which returns a referenced value by default – however, the function should return false if something went wrong during processing things in the function.

The function is declared as follows.

function &find($idx, $pref_array = false) {

    if ($pref_array === false)
        $pref_array = &$this->preferences;

    foreach ($pref_array as $key => $data) {
        if ($key == $idx) {
            return $pref_array[$idx];
        }
        else if (is_array($data)) {
            $res = &$this->find($idx, &$pref_array[$key]);
            if ($res !== false)
                return $res;
        }
    }

    return false;
}

PHP gives me a notice that "Only variable references should be returned by reference". Do I really need to put $result = false; in my code and return $result? That would be somehow ridiculous.

Thanks in advance for your help.

  • 写回答

1条回答 默认 最新

  • dongyin2390 2010-08-15 12:33
    关注

    I think that that is not a good way to code a general find function because it would be impossible to determine if a FALSE value returned from the function means that the value of the searched item was in fact FALSE or if the searched item was not found.

    If you know that FALSE are not legal values than its OK, otherwise you should implement the find function in a different way. For example this way:

    function find($idx, & $found_value, $pref_array = false) {
       // pseudocode
       if found:
         $found_value = $array[$idx]
         return true
       else:
         return false
    }
    

    This way you can always know if the requested item was found by checking the value returned from the function and if the returned value is TRUE you would have a reference to the found item in the variable referenced by the $found_value argument.

    Finally, this way you don't get any strange notice ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)