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

3

我有一个类测试,它初始化一个变量并注册一些匿名函数。一个函数用于显示变量testvar,另一个匿名函数用于将变量替换为另一个变量。问题是,当我第二次调用显示函数时,结果是a variable,但应该是another variable。希望您理解这个例子,非常感谢。

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");

为什么不直接使用display或replace函数呢? - Ibu
1个回答

1

由于您只传递了一个[变量名,新值]对,因此我会将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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接