本文章介紹的call_user_func是PHP的內置函數(shù),該函數(shù)允許用戶調用直接寫的函數(shù)并傳入一定的參數(shù),而call_user_func_array用一個數(shù)組作為參數(shù)調用一個回調函數(shù),返回值為回調函數(shù)執(zhí)行的結果或者為false,要傳遞參數(shù)給函數(shù),作為一個索引數(shù)組.
call_user_func() 函數(shù)類似于一種特別的調用函數(shù)的方法,使用方法如下:
- function test($a, $b) {
- echo $a*$b;
- }
- call_user_func('test', 4, 5);
- //---- echo 20 ----//
函數(shù)第一個參數(shù)為用戶自定義函數(shù),第二個參數(shù)為自定義函數(shù)中的參數(shù),調用類內部的方法比較奇怪,居然用的是array,不知道開發(fā)者是如何考慮的,當然省去了new,也是滿有新意的,代碼如下:
- class test {
- function demo($param) {
- echo $param;
- }
- }
- call_user_func(array("test", "demo"), "this is output result!");
- //--- echo this is output result! ---//
call_user_func_array()函數(shù)和call_user_func()很相似,只不過是換了一種方式傳遞了參數(shù),讓參數(shù)的結構更清晰,代碼如下:
- function test($b, $c) {
- echo $b;
- echo $c;
- }
- call_user_func_array('test', array("a", "b"));
- //------echo ab ---------//
call_user_func_array()函數(shù)也可以調用類內部的方法的,代碼如下:
- class class_demo {
- function fun_demo($param1, $param2) {
- echo $param1 + $param2;
- }
- }
- call_user_func_array(array('class_demo', 'fun_demo'), array("1", "2"));
- //---- echo 3 -----//
這里只是說了函數(shù)的使用方法,具體的事例可以在網上找找,代碼如下:
- <?php
- function debug($var, $val)
- {
- echo "***DEBUGGINGnVARIABLE: $varnVALUE:";
- if (is_array($val) || is_object($val) || is_resource($val)) {
- print_r($val);
- } else {
- echo "n$valn";
- }
- echo "***n";
- }
- //開源代碼Vevb.com
- $c = mysql_connect();
- $host = $_SERVER["SERVER_NAME"];
- call_user_func_array('debug', array("host", $host));
- call_user_func_array('debug', array("c", $c));
- call_user_func_array('debug', array("_POST", $_POST));
- ?>
|
新聞熱點
疑難解答