Assume this class code:
class Foo { function method() { echo 'works'; }}
Is there any way to store a reference to the method
method of a Foo
instance?
I'm just experimenting and fiddling around, my goal is checking whether PHP allows to call $FooInstance->method()
without writing $FooInstance->
every time. I know I could write a function wrapper for this, but I'm more interested in getting a reference to the instance method.
For example, this pseudo-code would theoretically store $foo->method
in the $method
variable:
$foo = new Foo();$method = $foo->method; //Undefined property: Foo::$method $method();
Apparently, as method
is a method and I'm not calling it with ()
the interpreter thinks I'm looking for a property thus this doesn't work.
I've read through Returning References but the examples only show how to return references to variables, not methods.
Therefore, I've adapted my code to store an anonymous function in a variable and return it:
class Foo { function &method() { $fn = function() { echo 'works'; }; return $fn; }}$foo = new Foo();$method = &$foo->method();$method();
This works, but is rather ugly. Also, there's no neat way to call it a single time, as this seems to require storing the returned function in a variable prior to calling it: $foo->method()();
and ($foo->method())();
are syntax errors.
Also, I've tried returning the anonymous function directly without storing it in a variable, but then I get the following notice:
Notice: Only variable references should be returned by reference
Does this mean that returning/storing a reference to a class instance method is impossible/discouraged or am I overlooking something?
Update: I don't mind adding a getter if necessary, the goal is just getting a reference to the method. I've even tried:
class Foo { var $fn = function() { echo 'works'; }; function &method() { return $this->fn; }}
But from the unexpected 'function' (T_FUNCTION)
error I'd believe that PHP wisely doesn't allow properties to store functions.
I'm starting to believe that my goal isn't easily achievable without the use of ugly hacks as eval()
.