使用__call()在重载函数中使用引用

时间:2012-07-03 12:53:39

标签: php reference overloading

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);

这导致:

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"

如何在PHP 5.4中完成上述操作(使用引用操作ref1和ref2)?

在PHP 5.3中,我使用了& $b->f(&$ref1, &$ref2);的语法(即使它已被弃用),但在PHP5.4中,这会引发致命的错误。

2 个答案:

答案 0 :(得分:6)

我设法找到了一个解决方案,虽然这是一个黑客攻击。

你仍然可以在数组中存储引用,并将数组作为参数传递,这将通过__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));

PHP手册指出:单独的函数定义足以通过引用正确传递参数。(http://php.net/manual/en/language.references.pass.php)不是__call()引用函数的情况!

答案 1 :(得分:0)

我把它取回来,这个实际上是,使用引用数组。这是我使用的完整代码:

class b
{
    public function __call($methodName, $arguments)
    {
        $a = new a();
        call_user_func_array(array(
            $a, $methodName
        ), $arguments[0]);
    }
}
$ref1 = 'X';
$ref2 = 'Y';
$b = new b();
$b->f( array( &$ref1, &$ref2));
var_dump($ref1, $ref2);

outputs

string(3) "foo"
string(3) "bar"

正如所料,没有任何警告或通知。