用匿名函数替换类中的变量



我有一个类测试,它启动一个变量并注册一些匿名函数。 一个用于显示变量 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");

由于您只传递一个 [variable_name, new_value] 对,我只想将替换函数更改为:

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

最新更新