如何在类中调用成员变量的__invoke方法 [英] How to call the __invoke method of a member variable inside a class

查看:137
本文介绍了如何在类中调用成员变量的__invoke方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 5.4.5,在这里。我试图调用一个存储为其他对象成员的对象。像这样(非常粗略地)

  class A {
function __invoke(){...}
}

class B {
private a = new A();
...
$ this-> a(); < - 运行时错误在这里
}

这产生了一个运行时错误,当然,因为没有方法称为a。但是如果我这样写电话:

 ($ this-> a)(); 

然后我得到一个语法错误。



当然,我可以写

$ $ p $ $ $ $ this-> a-> __ invoke();

但这看起来难以忍受,而且破坏了函子的重点。我只是想知道是否有更好的(或官方的)方式。

解决方案

有三种方法:
$ b

直接调用 __ invoke ,您已经提到过:

  $这 - > A-> __调用(); 

通过赋值给变量:

  $ a = $ this-> a; 
$ a();

通过使用 call_user_func

  call_user_func($ this-> a); 

最后一个可能是您要查找的内容。它具有与任何可调用函数一起工作的好处。


PHP 5.4.5, here. I'm trying to invoke an object which is stored as a member of some other object. Like this (very roughly)

class A {
    function __invoke () { ... }
}

class B {
    private a = new A();
 ...
    $this->a();  <-- runtime error here
}

This produces a runtime error, of course, because there's no method called a. But if I write the call like this:

($this->a)();

then I get a syntax error.

Of course, I can write

$this->a->__invoke();

but that seems intolerably ugly, and rather undermines the point of functors. I was just wondering if there is a better (or official) way.

解决方案

There's three ways:

Directly calling __invoke, which you already mentioned:

$this->a->__invoke();

By assigning to a variable:

$a = $this->a;
$a();

By using call_user_func:

call_user_func($this->a);

The last one is probably what you are looking for. It has the benefit that it works with any callable.

这篇关于如何在类中调用成员变量的__invoke方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆