Passing an instance method as argument in PHP

前端 未结 3 1967
我寻月下人不归
我寻月下人不归 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:48

    • Before PHP 5.4, there was no type named callable, so if you use it as a type hint, it means "the class named callable". If you use PHP >= 5.4, callable is a valid hint.

    • A callable is specified by a string describing the name of the callable (a function name or a class method name for example) or an array where the first element is an instance of an object and the second element is the name of the method to be called.

    For PHP < 5.4, replace

    public function add(callable $function)
    

    with:

    public function add($function)
    

    Call it with:

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

提交回复
热议问题