PHP's __invoke is a very useful feature that can maintain a single responsibility of a class
Example
class Invokable { public function __invoke() { echo '已被 invoke'; } }
Using
$invokable = new Invokable(); $invokable();
Invokeable classes can be injected into other classes
class Foo { protected $invokable; public function __construct(Invokable $invokable) { $this->invokable = $invokable; } public function callInvokable() { $this->invokable(); } }
Use $this->invokable(); to activate the Invokable class. The class will look for a method named invokable, so the following operation will report an error
$foo = new Foo($invokable); $foo->callInvokable(); // Call to undefined method Foo::invokable()
The following is correct Calling method
public function callInvokable() { // 优先推荐 call_user_func($this->invokable); // 可选 $this->invokable->__invoke(); // 可选 ($this->invokable)(); }
For more PHP related knowledge, please visit PHP tutorial!
The above is the detailed content of PHP Tip: Call Invoke type class in instance. For more information, please follow other related articles on the PHP Chinese website!