如何使用函数名称和参数作为变量调用适当的函数? PHP

时间:2015-08-28 09:39:27

标签: php mysql function oop parameter-passing

我想要获取ajax请求获取数据以对不同的表执行连接操作取决于参数和表名。

$.ajax({ url: '/my/site',
     data: {fun_name: 'join_user_and_state',
            param: '12,1'
      },
     type: 'post',
     success: function(output) {
                  alert(output);
              }
});

在服务器端,应该读取动作POST参数和函数名,相应的值应该指向要调用的方法,例如:

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
 }

我怎么称呼合适的功能?

或者有任何其他方法可以实现相同,我必须执行不同的连接查询取决于用户选择,如user_state,user_city,user_education,user_salary..etc(以及这些的所有组合也可能)< / strong>?这些列存在于他们自己的表中

1 个答案:

答案 0 :(得分:2)

您可以使用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....
}