php技能:在实例中挪用 Invoke 范例的类【php教程】,php
示例
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 范例的类的细致内容,更多请关注ki4网别的相干文章!