如何使用函数名和参数作为变量调用适当的函数? PHP
how to call appropriate function using function name and parameters as variables ? PHP
我想 ajax 请求获取数据以在不同的 table 上执行连接操作取决于参数和 table 名称。
$.ajax({ url: '/my/site',
data: {fun_name: 'join_user_and_state',
param: '12,1'
},
type: 'post',
success: function(output) {
alert(output);
}
});
服务端需要读取actionPOST参数和函数名,对应的值指向要调用的方法,例如:
if(!empty($_POST['param']) && !empty($_POST['fun_name'])) {
$param= $_POST['param']; $fun_name= $_POST['fun_name'];
// want to call proper function name with parametters from $fun_name and $param
// parameters could be 2 or 3 or more its depends upon user choice
// how to call
}
//definitions
join_user_and_state($user_id,$state_id)
{
// will do join query here with 2 tables
}
join_user_and_city($user_id,$city_id)
{
// will do join query here with 2 tables
}
join_user_and_state_and_city($user_id,$state_id,$city_id)
{
// will do join query here with 3 tables
}
如何调用合适的函数?
或者有任何其他方法可以实现相同的目的,我必须执行不同的不同 join 查询取决于用户的选择,例如 user_state、user_city、user_education, user_salary..etc(以及这些的所有组合也是可能的)?并且这些列存在于它们自己的 table
中
您可以使用 call_user_func()
示例:
if(!empty($_POST['param']) && !empty($_POST['fun_name'])) {
$param= $_POST['param']; $fun_name= $_POST['fun_name'];
$returnval = call_user_func($fun_name, explode(",", $param));
//handle return variable etc....
}
我想 ajax 请求获取数据以在不同的 table 上执行连接操作取决于参数和 table 名称。
$.ajax({ url: '/my/site',
data: {fun_name: 'join_user_and_state',
param: '12,1'
},
type: 'post',
success: function(output) {
alert(output);
}
});
服务端需要读取actionPOST参数和函数名,对应的值指向要调用的方法,例如:
if(!empty($_POST['param']) && !empty($_POST['fun_name'])) {
$param= $_POST['param']; $fun_name= $_POST['fun_name'];
// want to call proper function name with parametters from $fun_name and $param
// parameters could be 2 or 3 or more its depends upon user choice
// how to call
}
//definitions
join_user_and_state($user_id,$state_id)
{
// will do join query here with 2 tables
}
join_user_and_city($user_id,$city_id)
{
// will do join query here with 2 tables
}
join_user_and_state_and_city($user_id,$state_id,$city_id)
{
// will do join query here with 3 tables
}
如何调用合适的函数?
或者有任何其他方法可以实现相同的目的,我必须执行不同的不同 join 查询取决于用户的选择,例如 user_state、user_city、user_education, user_salary..etc(以及这些的所有组合也是可能的)?并且这些列存在于它们自己的 table
中您可以使用 call_user_func()
示例:
if(!empty($_POST['param']) && !empty($_POST['fun_name'])) {
$param= $_POST['param']; $fun_name= $_POST['fun_name'];
$returnval = call_user_func($fun_name, explode(",", $param));
//handle return variable etc....
}