How would one write PHP code to call all \"Callables\" with __invoke()
?
The desire here is pass by reference, which is deprecated with call_user_func[
It’s easy to implement for calling class member:
__invoke();
}
function passthrough_user(callable $callback) {
return call_user_func($callback);
}
function test_func() { return "func_string\n"; };
class test_obj {
public function test_method() {
return "obj_method\n";
}
}
class CallableWrapper {
private $inst, $meth;
public function __construct( $inst, $meth ) {
$this->inst = $inst;
$this->meth = $meth;
}
public function __invoke() {
echo $this->inst->{$this->meth}();
}
}
print_r("Call User Func Works:\n");
echo passthrough_user(function() { return "func_closure\n"; });
echo passthrough_user(array(new test_obj, 'test_method'));
echo passthrough_user('test_func');
print_r("\n__invoke rocks:\n");
echo passthrough_invoke( function() { return "func_closure\n"; } );
echo passthrough_invoke(
new CallableWrapper( new test_obj, 'test_method' )
);
// ⇒
// __invoke rocks:
// func_closure
// obj_method
For global scoped function is should be doable as well, but I reject to try to implement wrong patterns :)