I did some tests (to replace old code) using the __invoke magic method, and I'm not sure if this is an error or not:
Suppose we have a class:
class Calc { function __invoke($a,$b){ return $a*$b; } }
Maybe it works without problems:
$c = new Calc; $k = $c; echo $k(4,5);
However, if I want to have another class to hold an instance of this object, this does not work:
class Test { public $k; function __construct() { $c = new Calc; $this->k = $c;
The error occurs when we try to call it this:
$t = new Test; echo $t->k(4,5);
I know that the “solution” may be a function inside the Test class (named k) to “redirect” the call using call_user_func_array, but this is not elegant.
I need to save this instance inside a general class (for design purposes) and be able to call it as a function from other classes ... any suggestion?
Update:
I found something interesting (at least for my purposes):
If we assign a "class variable" to a local variable, it works:
$t = new Test; $m = $t->k; echo $m(4,5);
methods php invoke
lepe
source share