dqask02082 2016-09-19 14:37
浏览 47
已采纳

PHP - 通过引用传递抑制未定义的索引错误?

I just noticed the following behavior in my php code and I'm wondering why it's happening.

$array = array();

test_value($array['invalid_index']); // Error -> Notice: Undefined index: invalid_index in ...
test_reference($array['invalid_index']); //No error

function test_value($value){}
function test_reference(&$value){}

I was expecting both test_value and test_reference to throw the undefined index error but strangely the method by reference doesn't throw any error.

Why?

  • 写回答

1条回答 默认 最新

  • dsxml2169 2016-09-19 14:52
    关注

    Function parameters by-reference accept variables which haven't been declared previously; they are being declared by passing them as reference. This makes complete sense if you look at typical use cases of by-reference parameters:

    $foo = preg_match('/(.)/', 'bar', $baz);
    

    This function returns one value, which will be assigned to $foo. However, this function should also return the matches, which here is the third parameter $baz. Since a function can only return a single value at a time, additional "return" values are being realised by populating variables passed by reference.

    If you had to pre-initialise these variables, your code would look like this:

    $baz = null;
    $foo = preg_match('/(.)/', 'bar', $baz);
    echo $baz[0];
    

    This makes code more complicated than necessary; PHP hence doesn't require that such variables "exist" beforehand.

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

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办