如何使用PHP在实例中正确调用Invoke接口的类?

更新于
2026-09-30 15:31:58
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计280个文字,预计阅读时间需要2分钟。

如何使用PHP在实例中正确调用Invoke接口的类?

PHP的`__invoke()`特性非常有用,可保持类的单一职责。例如,`Invokable`类示例:`class Invokable { public function __invoke() { echo '已被invoke'; } }` 使用 `$invokable=new Invokable(); $invokable();`,`Invokeable`类可被注入至其他类。

PHP 的 __invoke 是一个很有用的特性,可以保持类的单一职责

示例

class Invokable { public function __invoke() { echo '已被 invoke'; } }

使用

$invokable = new Invokable(); $invokable();

Invokeable 类可以被注入到其他类中

class Foo { protected $invokable; public function __construct(Invokable $invokable) { $this->invokable = $invokable; } public function callInvokable() { $this->invokable(); } }

使用 $this->invokable(); 来激活 Invokable 类,类会去寻找名为 invokable 的方法,因此下面操作将会报错

$foo = new Foo($invokable); $foo->callInvokable(); // Call to undefined method Foo::invokable()

以下是正确的调用方法

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

更多PHP相关知识,请访问PHP教程!

以上就是php技巧:在实例中调用 Invoke 类型的类的详细内容,更多请关注自由互联其它相关文章!

如何使用PHP在实例中正确调用Invoke接口的类?

标签:类

本文共计280个文字,预计阅读时间需要2分钟。

如何使用PHP在实例中正确调用Invoke接口的类?

PHP的`__invoke()`特性非常有用,可保持类的单一职责。例如,`Invokable`类示例:`class Invokable { public function __invoke() { echo '已被invoke'; } }` 使用 `$invokable=new Invokable(); $invokable();`,`Invokeable`类可被注入至其他类。

PHP 的 __invoke 是一个很有用的特性,可以保持类的单一职责

示例

class Invokable { public function __invoke() { echo '已被 invoke'; } }

使用

$invokable = new Invokable(); $invokable();

Invokeable 类可以被注入到其他类中

class Foo { protected $invokable; public function __construct(Invokable $invokable) { $this->invokable = $invokable; } public function callInvokable() { $this->invokable(); } }

使用 $this->invokable(); 来激活 Invokable 类,类会去寻找名为 invokable 的方法,因此下面操作将会报错

$foo = new Foo($invokable); $foo->callInvokable(); // Call to undefined method Foo::invokable()

以下是正确的调用方法

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

更多PHP相关知识,请访问PHP教程!

以上就是php技巧:在实例中调用 Invoke 类型的类的详细内容,更多请关注自由互联其它相关文章!

如何使用PHP在实例中正确调用Invoke接口的类?

标签:类