Home > Backend Development > PHP Tutorial > PHP Tip: Call Invoke type class in instance

PHP Tip: Call Invoke type class in instance

藏色散人
Release: 2023-04-08 06:26:01
forward
2996 people have browsed it

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';
    }
}
Copy after login

Using

$invokable = new Invokable();
$invokable();
Copy after login

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();
    }
}
Copy after login

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()
Copy after login

The following is correct Calling method

public function callInvokable()
{
    // 优先推荐
    call_user_func($this->invokable);
    // 可选
    $this->invokable->__invoke();
    // 可选
    ($this->invokable)();
}
Copy after login

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!

Related labels:
php
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template