Is the call invocation method allowed in PHP?

For example, I have the following:

class A{ __invoke(){ // return an instance of class A itself } } 

can i do the following?

 new A()()()()... or (new A())()()()... 

and what explains here? suppose the PHP version is newer than 5.4

Well, I can give a little more explanation why I ask: I used ganon.php, which is an open source html dom parser. It uses syntax like $ html_node ('child_tag') to return another child $ html_node, where $ html_node is an instance of an object of class HTML_NODE. So I was thinking if I could use the chain to select in the nested html dom structure.

+6
source share
2 answers

I donโ€™t think that the behavior you describe really works even in PHP / 7:

 class A{ public function __invoke($arg){ echo __METHOD__ . "($arg) called" . PHP_EOL; } } $a = new A(); $a(0); $a(1)(2)(3); 
 A::__invoke(0) called A::__invoke(1) called Fatal error: Function name must be a string 

( demo )

You are probably confused by the function of the variable function . If foo() returns the string "bar", then foo()() is equal to bar() :

 class A{ public function __invoke(){ return 'hello'; } } function hello($name) { echo "Hello, $name!" . PHP_EOL; } $a = new A(); $a()('Jim'); 
 Hello, Jim! 

( demo )

You can associate this as long as your functions return more strings with valid function names, but neither __invoke nor classes play any role:

 function one() { return 'two'; } function two() { return 'three'; } function three() { return 'four'; } function four() { echo 'Done!'; } $a = one()()()(); 
 Done! 

( demo )

Note. All the code snippets above require PHP / 7, but they can be emulated with earlier versions using only the appropriate brackets and intermediate variables.


Update based on UlrichEckhardt comment: I missed returning an instance of class A comment itself. If you really do, the code really works:

 class A{ public function __invoke($arg){ echo __METHOD__ . "($arg) called" . PHP_EOL; return $this; } } $a = new A(); $a(0); $a(1)(2)(3); 

 class A{ public function __invoke($arg){ echo __METHOD__ . "($arg) called" . PHP_EOL; return $this; } } $a = new A(); $a(0); $a(1)(2)(3); 

( demo )

Of course, this is the PHP / 7 syntax. For older versions, you need helper variables that break the magic:

 $a = new A(); $b = $a(1); $c = $b(2); $d = $c(3); $d(4); 
+4
source

For PHP versions 7.0.0 - 7.0.4 you can use it as

 class A{ public function __invoke($x){ return __FUNCTION__."$x"; } } echo (new A())(2); 

Output:

 __invoke2 
+4
source

All Articles