php 提示Only variables should be assigned by reference?

Strict Standards: Only variables should be assigned by reference

clipboard.png

函数的返回值似乎不能引用

阅读 11.2k
5 个回答

当前php版本不影响功能错误提示,关闭错误提示就可以了,但不保证在将来的版本不失效。

或者修改成这样就不会报错了

function &getArr(){
    static $arr = [3,4,6];
    return $arr;
}

$arr2 = &getArr();
$arr2[0] = 100;
var_dump($arr2);

$arr3 = &getArr();
var_dump($arr3);

一般不要使用函数返回引用,详见php官方文档

Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.

不要企图通过返回引用提高程序性能,引擎会自动进行优化,只有在有明确的里有的情况下才可以使用!

这里之所以报警告,是因为用法错误

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

也就是说必须要同时在函数定义和使用的时候前面都加&,正如 @咪蛾 所说 。

没毛病啊 可以输出,都是变量引用同一个地址

是同一指针地址,应该没有错

array(3) { [0]=> int(100) [1]=> int(4) [2]=> int(6) }

从编程角度来讲,还是不要将局部变量引用出来的好。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题