动态调用函数,从变量传递参数 [英] call function dynamically, passing arguments from variable
问题描述
这是我的ajax_handle文件:
if($ _SERVER ['HTTP_X_REQUESTED_WITH']!==XMLHttpRequest)
{
回显错误;
exit();
$ req = explode(_,$ _ POST ['req']);
$ className = $ req [0]。 控制器;
$ methodName = $ req [1];
$ file =application / controllers /。 $ className。 .php;
require_once $ file;
if($ _POST ['data']){
var_dump($ _ POST ['data']);
}
$ controller = new $ className;
$ result = $ controller-> $ methodName();
echo json_encode($ result);
我将参数作为$ _POST ['data']变量中的任何数组发送。我不知道什么是将它们传递给(动态)$ methodName函数的最好方法。
我想你可以传递 $ _ POST ['data']
作为动态方法。您可以让
动态方法接受数组,但最初设置了默认值,以便您可以轻松处理并且
验证它们。例子:
class AController
{
public function dynamicMethod($ params)
{
//设置默认值,但允许它们被$ params覆盖
$ locals = array_merge(array(
'name'=>'John Doe',
'address' =>'无处',
),$ params);
//做东西并返回结果。例如:
return array('nameAndAddress'=> $ locals ['name']。'lives at'。$ locals ['address']);
}
}
您也可以选择使用 extract()
将
名称
和地址
放入真实的局部变量中。
在你的ajax句柄中:
$ controller = new $ className;
$ result = $ controller-> $ methodName($ _ POST ['data']);
echo json_encode($ result);
有了这些说明,请注意@Sven所说的是正确的。您当前的方法中存在一些安全性
问题。
here is my ajax_handle file:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] !== "XMLHttpRequest")
{
echo "Error";
exit();
}
$req = explode("_",$_POST['req']);
$className = $req[0] . "Controller" ;
$methodName = $req[1];
$file = "application/controllers/" . $className . ".php" ;
require_once $file;
if ($_POST['data']) {
var_dump($_POST['data']);
}
$controller = new $className;
$result = $controller->$methodName();
echo json_encode($result);
I send the arguments as any array in the $_POST['data'] variable. i have no idea what would be the best way to pass them to the (dynamic) $methodName function.
I suppose you could just pass $_POST['data']
as is to your dynamic method. You can have the
dynamic method accept the array but initially set default values so you can easily handle and
validate them. Example:
class AController
{
public function dynamicMethod($params)
{
// Set default values but allow them to be overridden by $params
$locals = array_merge(array(
'name' => 'John Doe',
'address' => 'Nowhere',
), $params);
// Do stuffs and return result. Example:
return array('nameAndAddress' => $locals['name'] . ' lives at ' . $locals['address']);
}
}
You also opt to use extract()
to convert the
name
and address
above into real local variables.
In your ajax handle:
$controller = new $className;
$result = $controller->$methodName($_POST['data']);
echo json_encode($result);
With all these said, please note that what @Sven is saying is correct. There are some security issues in your current approach.
这篇关于动态调用函数,从变量传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!