我有几个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
将取testOne
或testTwo
的值,这将"告诉"代码要运行什么函数。然后,您要做的是使用变量函数名调用函数,并将返回的值捕获到变量中:
$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
的值应该是testOne
或testTwo
此处为call_user_func
的文档