Passing an instance method as argument in PHP

巧了我就是萌 提交于 2019-11-27 14:57:53
rid
  • 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'));

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.

I don't think you can specify a callable this way...

Try

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

And see http://php.net/manual/en/language.types.callable.php too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!