I'm working a Thread wrapper class that can take in a function and call that function in a new thread. This my class so far:
public function __construct($cbCallback, $aParameters) {
$this->cbCallback = $cbCallback;
$this->aParameters = $aParameters;
$this->return = false;
}
public function run() {
if (is_array($this->cbCallback)) {
$this->return = call_user_func($this->cbCallback, ...($this->aParameters));
}
else {
$this->return = $this->cbCallback(...($this->aParameters));
}
}
And this works using the call_user_func portion when taking in a callback. I would like to overload the class so that it can also take in a closure instead of a callback array. I've run into trouble storing the anonymous function as a class variable: it is always stored as null.
I put some debugging statements in the constructor:
echo "Paramater test 1: " . json_encode($cbCallback);
$this->cbCallback = $cbCallback;
echo "Paramater test 2: " . json_encode($cbCallback);
echo "Variable test: " . json_encode($this->cbCallback);
This yields the output:
Paramater test 1: {}
Paramater test 2: {}
Variable test: null
I have also tried making $cbCallback
pass by reference with &$cbCallback
, which just results in a error that the object cannot be passed by reference.
I feel like either there is a special rule with anonymous functions, or something wonky is going on. Why can't I store the anonymous function into $this->cbCallback? Is there any way to store the anonymous function in a (non static) class variable or something similar that will work the same way when I need to call that function?
P.S. I'm on PHP v5.6
I've finally tracked down the issue I was having. It turns out it is an issue with the pthreads library.
The specified code works perfectly so long as you do not extend the Thread
class.
I found this bug report on php's website: https://bugs.php.net/bug.php?id=67506
Then posted it to krakjoe's github: https://github.com/krakjoe/pthreads/issues/355
Turns out he had fixed the issue a couple hours before me posting, so to fix this issue, make sure you are running pthreads v2.0.9+.