通过引用传递不能按预期工作

时间:2014-08-31 13:41:25

标签: php reference

为什么在下面简化的插件系统示例中,通过引用($ data)传递不起作用($ content未被修改)?

class Plugins
{
    public static function runhook()
    {
       $args = func_get_args();
       $hook = array_shift($args);
       foreach ($args as &$a); // be able to pass $args by reference
       call_user_func_array(array('Plugin', $hook), $args);
    }

}

class Plugin
{
    public static function modifData(&$data)
    {
       $data = 'Modified! :'.$data;
    }
}

class Application
{
    public $content;

    public function __construct()
    {
       $this->content = 'Content from application...';
    }

    public function test()
    {
       echo $this->content; // return 'Content from application...'
       Plugins::runHoook('modifData', $this->content);
       echo $this->content; // return 'Content from application...' instead of 'Modified! :Content from application...'

    }
}

$app = new Application();
$app->test();

正如您所看到的,$ this->内容应该由插件类的runHook()函数在后台调用的modifData()进行修改。但由于一个奇怪的原因,没有任何预期发生,变量仍然停留在原来的状态......也许我错了?

提前感谢您的帮助......

1 个答案:

答案 0 :(得分:0)

不可能使用可变数量的参数(另请参阅https://stackoverflow.com/a/7035513/684353)。

你可以用这个来实现它(重复这个你想要的参数数量,这不应该太多):

<?php

class Plugins
{
    public static function runHook($hook, &$param1)
    {
       $args = func_get_args();
    //   call_user_func_array(array('Plugin', $hook), [$param1]); // doesn't work, probably can fix this but didn't seem necessary 
       Plugin::$hook($param1);
    }

}

class Plugin
{
    public static function modifData(&$data)
    {
       $data = 'Modified! :'.$data;
    }
}

class Application
{
    public $content;

    public function __construct()
    {
       $this->content = 'Content from application...';
    }

    public function test()
    {
       echo $this->content; // return 'Content from application...'
       Plugins::runHook('modifData', $this->content);
       echo $this->content; // return 'Content from application...' instead of 'Modified! :Content from application...'

    }
}

$app = new Application();
$app->test();

或者等待PHP 5.6并希望... token允许这样做。