Replace variable in class by anonymous function

Question

i have a class test that initiates a variable and register some anonymous functions. a function to display the variable testvar and another anonymous function to replace the variable with another variable. The problem is, wenn i call display the second time, the result is a variable but it should be another variable. I hope you understand the example and thank you very much.

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

Show source
| class   | php   | anonymous-function   2017-01-07 00:01 1 Answers

Answers to Replace variable in class by anonymous function ( 1 )

  1. 2017-01-07 00:01

    As you are passing only one [variable_name, new_value] pair, I would just change the replace function to this:

    private function replace($options) {
        $this->$options[0] = $options[1];
    }
    

    But, if you want to keep your code as it is, it will work if you replace this

    $test->call_hook("replace",array("testvar", "another variable"));
    

    with this

    $test->call_hook("replace",array("testvar" => "another variable"));
                                              ^^^^
    

    This will make sure that the foreach statement will match your parameters correctly, as you are parsing the values as key => value pairs

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

Leave a reply to - Replace variable in class by anonymous function

◀ Go back