TheBat
TheBat

Reputation: 1044

Store static function of a class in a variable

In PHP, I have a class that takes in a function object and calls that function in a thread: see the answer to this question.

It works well with anonymous functions, however, I want to use this functionality with a static function of a different class:

    $thThread = new FunctionThreader(OtherClass::static_function, $aParams);

This throws an error Undefined class constant static_function on line x

I have tried:

    $fFunction = OtherClass::static_function;
    $thThread = new FunctionThreader($fFunction, $aParams);

And I get the same error.

So is there anyway to store this static function into $fFunctionor to simply reference it as a function object?

Upvotes: 3

Views: 1200

Answers (2)

hek2mgl
hek2mgl

Reputation: 158040

In PHP you would usually use a callback for this:

$callback = array('ClassName', 'methodName');
$thThread = new FunctionThreader($callback, $aParams);

If FunctionThreader::__construct() does only accept a Closure and you have no influence on it's implementation, then you can wrap the static function call in a Closure:

$closure = function() { return ClassName::methodName(); };
$thThread = new FunctionThreader($closure, $aParams);

Upvotes: 2

Lauri Orgla
Lauri Orgla

Reputation: 561

You could define a lambda function which calls your static function. Or simply store function name as a string in that variable. You would also have to implement a handler code for the class that calls a function from variable.

Resources: http://php.net/manual/en/function.forward-static-call-array.php

https://www.php.net/manual/en/function.func-get-args.php

Example for anonymous function:

<?php 

$function = new function(){
   return forward_static_call_array(['class', 'function'], func_get_args());
};

?>

Testes this, works flawlessly.

Upvotes: 0

Related Questions