php 为什么会出现“预期为参考,给定值”的错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3637164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does the error "expected to be a reference, value given" appear?
提问by yury-n
It fires out when I try to call function with argument by reference
当我尝试通过引用调用带有参数的函数时它会触发
function test(&$a) ...
through
通过
call_user_func('test', $b);
回答by Daniel Vandersluis
call_user_func
can onlypass parameters by value, not by reference. If you want to pass by reference, you need to call the function directly, or use call_user_func_array
, which accepts references (however this may not work in PHP 5.3 and beyond, depending on what part of the manual look at).
call_user_func
可以仅通过值传递参数,而不是通过引用。如果要通过引用传递,则需要直接调用该函数,或者使用call_user_func_array
,它接受引用(但是这在 PHP 5.3 及更高版本中可能不起作用,具体取决于手册查看的部分)。
回答by Jim W.
From the manual for call_user_func()
来自call_user_func()的手册
Note that the parameters for call_user_func() are not passed by reference.
请注意, call_user_func() 的参数不是通过引用传递的。
So yea, there is your answer. However, there is a way around it, again reading through the manual
所以是的,这就是你的答案。但是,有一种方法可以解决它,再次阅读手册
call_user_func_array('test', array(&$b));
Should be able to pass it by reference.
应该可以通过引用传递它。
回答by rhalff
I've just had the same problem, changing (in my case):
我刚刚遇到了同样的问题,正在改变(就我而言):
$result = call_user_func($this->_eventHandler[$handlerName][$i], $this, $event);
to
到
$result = call_user_func($this->_eventHandler[$handlerName][$i], &$this, &$event);
seem to work just fine in php 5.3.
似乎在 php 5.3 中工作得很好。
It's not even a workaround I think, it's just doing what is told :-)
我认为这甚至不是解决方法,它只是按照指示做:-)
回答by reubano
You need to set the variable equal to the result of the function, like so...
您需要将变量设置为等于函数的结果,就像这样......
$b = call_user_func('test', $b);
and the function should be written as follows...
并且函数应该写成如下...
function test($a) {
...
return $a
}
The other pass by reference work-a-rounds are deprecated.
不推荐使用其他通过引用工作的循环。
回答by Tel
You might consider the closure concept with a reference variable tucked into the "use" declaration. For example:
您可以考虑在“use”声明中包含一个引用变量的闭包概念。例如:
$note = 'before';
$cbl = function( $msg ) use ( &$note )
{
echo "Inside callable with $note and $msg\n";
$note = "$msg has been noted";
};
call_user_func( $cbl, 'after' );
echo "$note\n";
Bit of a workaround for your original problem but if you have a function that needs call by reference, you can wrap a callable closure around it, and then execute the closure via call_user_func().
解决您的原始问题的一点解决方法,但如果您有一个需要通过引用调用的函数,您可以在它周围包装一个可调用的闭包,然后通过 call_user_func() 执行闭包。