php - Cannot use invoke magic method within another object -
i have experienced think it's bug, i'm not sure. come here ask people know more me, is php bug? @ following lines:
<h1>tests</h1> <?php class foo { public function __invoke() { return 'called correctly'; } } class boo { public function __construct() { $this->foo = new foo(); } } $foo = new foo(); echo $foo(); echo "<br><br><hr><br><br>"; $boo = new boo(); echo $boo->foo();
according the specification, since the __invoke() method called when script tries call object function
, should obtain this:
called correctly
called correctly
but last echo not executed. instead, this:
php fatal error: call undefined method boo::foo() in [...]/index.php on line 26
is bug or expected behaviour? if it's bug, how submit highly appreciated.
edit based on jon answer show further ugly behaviour
class doo { public function __construct() { // foo class same 1 defined before $test = new foo(); echo $test(); // echos correctly echo "<br><br><hr><br><br>"; $this->foo = $test; echo $this->foo(); // error. heisenbehaviour? } } $boo = new doo();
it not bug, , not limited foo
being object defines __invoke
. same error callable:
class foo { private $bar = 'rand'; public function __construct() { $this->bar(); // won't work } }
you need either write 2 lines, or use call_user_func
:
// #1 $boo = new boo(); $foo = $boo->foo; $foo(); // #2 $boo = new boo(); call_user_func($boo->foo);
Comments
Post a Comment