Passing an instance method as argument in PHP

前端 未结 3 1963
我寻月下人不归
我寻月下人不归 2020-12-03 13:29

I would like to create a Listener class

class Listener {
    var $listeners = array();
    
    public function add(callable $function) {
        $this->li         


        
3条回答
  •  北海茫月
    2020-12-03 13:59

    Methods and properties have separate namespaces in PHP, which is why $this->bar evaluates to null: You're accessing an undefined property.

    The correct way to create an array in the form of array($object, "methodName"):

    Passing the callback correctly:

    $listener->add(array($this, 'bar'));  
    

    The type hint you have given is okay—as of PHP 5.4, that is.

提交回复
热议问题