Jon*_*eig 4 php overloading reference
class a
{
public function f(&$ref1, &$ref2)
{
$ref1 = 'foo';
$ref2 = 'bar';
}
}
class b
{
public function __call($methodName, $arguments)
{
$a = new a();
call_user_func_array(array(
$a, $methodName
), $arguments);
}
}
$ref1 = 'X';
$ref2 = 'Y';
$b = new b();
$b->f($ref1, $ref2);
var_dump($ref1, $ref2);
Run Code Online (Sandbox Code Playgroud)
这导致:
PHP Warning: Parameter 1 to a::f() expected to be a reference, value given in /home/jon/sync_workspace/bugsync/tests/test.php on line 18
PHP Stack trace:
PHP 1. {main}() /test.php:0
PHP 2. b->f() /test.php:23
PHP 3. b->__call() /test.php:23
PHP 4. call_user_func_array() /test.php:17
string(1) "X"
string(1) "Y"
Run Code Online (Sandbox Code Playgroud)
如何在PHP 5.4中完成上述操作(使用引用操作ref1和ref2)?
在PHP 5.3中,我使用了&语法$b->f(&$ref1, &$ref2);(即使它已被弃用),但在PHP5.4中,这会引发致命错误.
我设法找到了解决方案,虽然它是一个黑客.
您仍然可以将引用存储在数组中,并将该数组作为参数传递,该参数将通过__call()生存
class b
{
public function __call($methodName, $arguments)
{
$a = new a();
call_user_func_array(array(
$a, $methodName
), reset($arguments));
}
}
$ref1 = 'X';
$ref2 = 'Y';
$b = new b();
$b->f(array(&$ref1, &$ref2));
Run Code Online (Sandbox Code Playgroud)
PHP手册说明:单独的函数定义足以通过引用正确传递参数.(http://php.net/manual/en/language.references.pass.php)显然不是__call()引用函数的情况!