簡體   English   中英

如何使用函數名稱和參數作為變量來調用適當的函數? 的PHP

[英]how to call appropriate function using function name and parameters as variables ? PHP

我想提出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)執行不同的不同聯接查詢(以及所有這些組合也是可能的) 這些列存在於它們自己的表中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM