Php 按引用传递未按预期工作
为什么在下面的简化插件系统示例中,按引用传递($data)不起作用($content未修改) 如您所见,$this->内容应该由插件类的runHook()函数在后台调用的modifData()修改。但是由于一个奇怪的原因,没有发生预期的事情,变量停留在其原始状态。。。也许我错了Php 按引用传递未按预期工作,php,reference,Php,Reference,为什么在下面的简化插件系统示例中,按引用传递($data)不起作用($content未修改) 如您所见,$this->内容应该由插件类的runHook()函数在后台调用的modifData()修改。但是由于一个奇怪的原因,没有发生预期的事情,变量停留在其原始状态。。。也许我错了 提前感谢您提供的任何帮助…参数数量可变时不可能实现(另请参阅) 您可以通过以下方法实现它(对于您期望的参数数量,重复此操作,不应该太多): Plugins::runHoook不应该是Plugins::runHook?这是
提前感谢您提供的任何帮助…参数数量可变时不可能实现(另请参阅) 您可以通过以下方法实现它(对于您期望的参数数量,重复此操作,不应该太多):
Plugins::runHoook
不应该是Plugins::runHook
?这是因为您只通过引用传递Plugin类。Plugins::runHook没有收到引用Wit,你可以传递整个对象,因为对象总是通过引用传递。@Fred ii-Oops这只是一个输入错误…@Pinoniq感谢我在原始代码中尝试的解释哦,好的,所以如果不可能,我可以搜索很长时间!感谢您的解释,我将根据您的示例尝试以下内容:)
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();
<?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();