php怎麼實現動態傳參數?

來源:互聯網
上載者:User
先貼代碼,代碼精簡了。
$invoker_function($argus);}}?>

描述:
程式是在ThinkPHP開發,目的是把Cache的get方法接收的參數轉寄到指定的方法上,
最後一行:其中D方法是ThinkPHP內建的方法用的是單例模式。如果不加參數$argus是可以正常調用的。

問題:
現在想傳遞參數,比如get("name","age"),完整的傳遞到 D($invoker_class)->$invoker_function(“name”,"age")上,有什麼辦法。

call_user_func 看起來像是可以,不過看不出來怎麼用。

求解。


回複討論(解決方案)

call_user_func_array(array(D($invoker_class), $invoker_function), $argus);

call_user_func_array(array(D($invoker_class), $invoker_function), $argus);


哈哈,謝謝斑竹,發帖前測試一直不成功原來是因為call_user_func_array的第二個參數必須使用數組,如果不使用數組就會沒有任何反映。。

最後完整的代碼如下::代碼爛,見諒。。
CacheModel.class.php Cache模型檔案
caculate($argus);$base_str= md5($str);if($this->cache_arr[$invoker_class][$invoker_function]["key"] == $base_str){echo "命中cache 沒有查詢";//命中cachereturn $this->cache_arr[$invoker_class][$invoker_function]["value"];}$new_invoker_class= str_replace("Model","", $invoker_class);$new_invoker_function= $invoker_function."_setCache";$rs = call_user_func_array(array(D($new_invoker_class), $new_invoker_function), $argus);$this->cache_arr[$invoker_class][$invoker_function]["key"] = $base_str;$this->cache_arr[$invoker_class][$invoker_function]["value"] = $rs;return $rs;}/** *  * 遞迴計算所有的參數,判定參數是否發生改變 */private function caculate(&$argus){$str = "";foreach ($argus as $key => $value){if(is_array($value)){$str .= $this->caculate($argus[$key]);}else{$str .= $value;}}return $str;}}?>


測試模型
TestModel.class.php
cache = D("Cache");}public function run($a,$b,$c){return $this->cache->get($a,$b,$c);}public function run_setCache($a,$b,$c){return "設定3參數預定值
";}public function run2(){return $this->cache->get();}public function run2_setCache(){return "設定空預定值
";}}?>


測試案例
TestAction.class.php
run("a","b","c");echo $test->run("a","b","c");echo $test->run("a","b","c");$test2 = D("Test");echo $test2->run("a","b","c");echo $test2->run2();echo $test2->run2();echo $test2->run2();}}?>



測試結果:
設定3參數預定值命中cache 沒有查詢設定3參數預定值命中cache 沒有查詢設定3參數預定值命中cache 沒有查詢設定3參數預定值設定空預定值命中cache 沒有查詢設定空預定值命中cache 沒有查詢設定空預定值


達到預定設想,,謝謝斑竹解答。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.