我有一个类测试,它启动一个变量并注册一些匿名函数。显示变量 testvar 的函数和另一个用另一个变量替换变量的匿名函数。问题是,我第二次调用显示,结果是变量,但它应该是另一个变量。我希望你理解这个例子,非常感谢你。
class test {
private $functions = array();
private $testvar;
function __construct() {
$this->testvar = "a variable";
$this->functions['display'] = function($a) { return $this->display($a); };
$this->functions['replace'] = function($options) { return $this->replace($options); };
}
private function display($a) {
return $this->$a;
}
private function replace($options) {
foreach($options as $a => $b) {
$this->$a = $b;
}
}
public function call_hook($function, $options) {
return call_user_func($this->functions[$function], $options);
}
}
$test = new test();
echo $test->call_hook("display","testvar");
$test->call_hook("replace",array("testvar","another variable"));
echo $test->call_hook("display","testvar");
答案 0 :(得分:1)
由于您只传递了一个 [variable_name,new_value] 对,我只需将 replace 函数更改为:
private function replace($options) {
$this->$options[0] = $options[1];
}
但是,如果你想保持你的代码不变,那么如果你替换这个
,它将会起作用$test->call_hook("replace",array("testvar", "another variable"));
用这个
$test->call_hook("replace",array("testvar" => "another variable"));
^^^^
这将确保foreach语句正确匹配您的参数,因为您正在将值解析为 key =>值对
foreach($options as $a => $b) {
^^^^^^^^
$this->$a = $b;
}