问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/17842359/call-function-dynamically-passing-arguments-from-variable