Php 用匿名函数替换类中的变量
我有一个类测试,它启动一个变量并注册一些匿名函数。一个函数显示变量testvar,另一个匿名函数用另一个变量替换变量。问题是,如果我第二次调用display,结果是一个变量,但它应该是另一个变量。我希望你能理解这个例子,并非常感谢你Php 用匿名函数替换类中的变量,php,class,anonymous-function,Php,Class,Anonymous Function,我有一个类测试,它启动一个变量并注册一些匿名函数。一个函数显示变量testvar,另一个匿名函数用另一个变量替换变量。问题是,如果我第二次调用display,结果是一个变量,但它应该是另一个变量。我希望你能理解这个例子,并非常感谢你 class test { private $functions = array(); private $testvar; function __construct() { $this->testvar = "a
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");
由于您只传递一个[variable\u name,new\u 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=>value对
为什么不按原样使用显示或替换功能?
foreach($options as $a => $b) {
^^^^^^^^
$this->$a = $b;
}