Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

php - How to call the __invoke method of a member variable inside a class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...