Thread Wrapper Class for a Function with variable arguments in PHP

为君一笑 提交于 2019-12-25 00:36:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!