1

Ran into this oddity

class my_class {
    public $error_handler;

    public function __construct($error_handler = NULL) {
        $this->error_handler = $error_handler;
    }

    public function error($description) {    //<- calling this breaks PHP
        if ($this->error_handler === NULL) die($description);   
        $this->error_handler($description);
    }

    public function error2($description) {    //<- calling this works fine
        if ($this->error_handler === NULL) die($description);
        $handler = $this->error_handler;
        $handler($description);
    }

    public function spawn_error() {
        $this->error("I'm a feature, not a bug.");  
    }
}

$special_error_handler = function($description) {
    die("special handling for $description");   
};

$my_obj = new my_class($special_error_handler);

$my_obj->spawn_error();

When calling my_class::error, it throws an undefined method error, calling my_class::error2 works fine. I mean.. technically its correct that my_class doesn't have a method named error_handler but it does have a variable storing an anonymous function, why doesn't it look there?

Other than using a temporary variable, is there a special way to call anonymous functions stored in class variables?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • 2
    You can avoid using a temporary variable with `($this->error_handler)($description);`, but I don't know why it doesn't work without the parentheses. I should be evaluated left to right. Right? – jh1711 Sep 09 '18 at 23:34

0 Answers0