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

Replace variable in class by anonymous function

我有一个 class 测试,它启动一个变量并注册一些匿名函数。一个显示变量 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] 对,我会改变 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 pairs

foreach($options as $a => $b) {
                    ^^^^^^^^
    $this->$a = $b;
}