PHP函数将数据返回到数组


PHP Function return data to an array

我有几个php函数通过同一个变量返回各种数据,该变量应该分配给一个数组。现在我想通过检查$_POST来执行函数,并将$data分配给$response多维数组。。。有办法做到这一点吗???

$functionname = $_POST['functionname'];
function testOne(){
$data = array('test'=>'value1');
return $data;
}
function testTwo(){
$data = array('test'=>'value2');
return $data;
}
//Here I need to execte each functions and return $data
$response = array('result' => array('response'=>'success'),'clients' => $data);
print_r($response);

函数只有在被调用时才运行。您尚未调用任何一个函数。

从代码的外观来看,我假设$functionname将取testOnetestTwo的值,这将"告诉"代码要运行什么函数。然后,您要做的是使用变量函数名调用函数,并将返回的值捕获到变量中:

$functionname = $_POST['functionname'];
//function definitions
$response = array('result' => array('response'=>'success'), 'clients' => $functionname());

请参阅文档,好吧。。。文档。

您可以直接调用数组内部的函数。

$response = array('result' => array('response'=>'success'),'clients' => testTwo());

现在在$response['clients']中,该值将包含array('test'=>'value2');

或者如果您想通过用户输入来调用函数。如果

if $_POST['funtionname'] = 'testOne'; then execute testOne();
if $_POST['funtionname'] = 'testTwo'; then execute testTwo();

那么您可以在这里使用CCD_ 8。像这样。

$_POST['funtionname'] = 'testOne';
call_user_func($_POST['functionname']);
//this will execute testOne(); and depending upon the value it consist, it will execute the corresponding function.

如果这就是你的意思。如果我理解错了,请纠正我。

我认为您希望从$functionname变量中调用函数。。如果是这样,这就是你的做法:

$data = call_user_func($functionname);
$response = array('result' => array('response'=>'success'),'clients' => $data);

在这种情况下,$functionname的值应该是testOnetestTwo

此处为call_user_func的文档