问题
The idea here is to make a class that constructs with a function and an array of parameters and calls that function in a new thread.
This is my class so far:
class FunctionThread extends Thread {
public function __construct($fFunction, $aParameters){
$this->fFunction = $fFunction;
$this->aParameters = $aParameters;
}
public function run(){
$this->fFunction($this->aParmeters[0], $this->aParmeters[1], ...);
}
}
Obviously the run function is incorrect, which brings me to my question:
Assuming the array is guaranteed to have the proper number of elements to match the function that is being called, How can I call a function in PHP with an unknown number of arguments that are stored in an array?
Edit: Also I have no access to the contents of the given function so it cannot be edited.
Edit 2: I'm looking for something similar to scheme's curry function.
回答1:
As of PHP 5.6, this is now possible. Arrays can be expanded into the argument list using the ... operator like so:
<?
class FunctionThread extends Thread {
public function __construct($fFunction, $aParameters){
$this->fFunction = $fFunction;
$this->aParameters = $aParameters;
}
public function run(){
$this->fFunction(... $this->aParmeters);
}
}
?>
See here for more information
回答2:
I think that function should accept in its case the arg array
class FunctionThread extends Thread {
public function __construct($fFunction, $aParameters){
$this->fFunction = $fFunction;
$this->aParameters = $aParameters;
}
public function run(){
$this->fFunction($this->aParmeters);
}
public function fFunction($arr){
$var0 = $arr[0];
$var1 = $arr[1];
...
do
..
}
}
来源:https://stackoverflow.com/questions/25186885/thread-wrapper-class-for-a-function-with-variable-arguments-in-php