Store static class function in variable
In PHP, I have a class that takes a function object and calls that function on a stream: see the answer to this question .
This works well with anonymous functions, however I want to use this function with a static function of another class:
$thThread = new FunctionThreader(OtherClass::static_function, $aParams);
This raises the error Undefined class constant static_function on line x
I tried:
$fFunction = OtherClass::static_function;
$thThread = new FunctionThreader($fFunction, $aParams);
And I am getting the same error.
So, is it worth storing this static function in $fFunction
or just referring to it as a function object?
source to share
In PHP, you usually use a callback for this:
$callback = array('ClassName', 'methodName');
$thThread = new FunctionThreader($callback, $aParams);
If FunctionThreader::__construct()
it only accepts Closure
, and you have no influence on its implementation, then you can wrap a static function call in Closure
:
$closure = function() { return ClassName::methodName(); };
$thThread = new FunctionThreader($closure, $aParams);
source to share
You can define a lambda function that calls your static function. Or just store the function name as a string in this variable. You will also have to implement handler code for the class that calls the function from the variable.
Resources: http://php.net/manual/en/function.forward-static-call-array.php
http://ee1.php.net/manual/en/function.func-get-args.php
An example of an anonymous function:
<?php
$function = new function(){
return forward_static_call_array(['class', 'function'], func_get_args());
};
?>
Tests this, works flawlessly.
source to share