当前位置:首页 > PHP教程 > php函数 > 列表

PHP函数call_user_func和call_user_func_array的使用

发布:smiling 来源: PHP粉丝网  添加日期:2014-09-12 14:55:53 浏览: 评论:0 

本文章介绍的call_user_func是PHP的内置函数,该函数允许用户调用直接写的函数并传入一定的参数,而call_user_func_array用一个数组作为参数调用一个回调函数,返回值为回调函数执行的结果或者为false,要传递参数给函数,作为一个索引数组.

call_user_func() 函数类似于一种特别的调用函数的方法,使用方法如下:

  1. function test($a, $b) { 
  2.     echo $a*$b; 
  3. } 
  4. call_user_func('test', 4, 5); 
  5. //---- echo 20 ----// 

函数第一个参数为用户自定义函数,第二个参数为自定义函数中的参数,调用类内部的方法比较奇怪,居然用的是array,不知道开发者是如何考虑的,当然省去了new,也是满有新意的,代码如下:

  1. class test { 
  2.     function demo($param) { 
  3.         echo $param; 
  4.     } 
  5. } 
  6. call_user_func(array("test", "demo"), "this is output result!"); 
  7. //--- echo this is output result! ---//  

call_user_func_array()函数和call_user_func()很相似,只不过是换了一种方式传递了参数,让参数的结构更清晰,代码如下:

  1. function test($b, $c) { 
  2.     echo $b; 
  3.     echo $c; 
  4. } 
  5. call_user_func_array('test', array("a", "b")); 
  6. //------echo ab ---------//  

call_user_func_array()函数也可以调用类内部的方法的,代码如下:

  1. class class_demo { 
  2.     function fun_demo($param1, $param2) { 
  3.         echo $param1 + $param2; 
  4.     } 
  5. } 
  6. call_user_func_array(array('class_demo', 'fun_demo'), array("1", "2")); 
  7. //---- echo 3 -----//  

这里只是说了函数的使用方法,具体的事例可以在网上找找,代码如下:

  1. <?php 
  2. function debug($var, $val)  
  3. { 
  4.     echo "***DEBUGGINGnVARIABLE: $varnVALUE:"; 
  5.     if (is_array($val) || is_object($val) || is_resource($val)) { 
  6.         print_r($val); 
  7.     } else { 
  8.         echo "n$valn"; 
  9.     } 
  10.     echo "***n"; 
  11. } 
  12. //开源代码phpfensi.com 
  13. $c = mysql_connect(); 
  14. $host = $_SERVER["SERVER_NAME"]; 
  15.  
  16. call_user_func_array('debug', array("host", $host)); 
  17. call_user_func_array('debug', array("c", $c)); 
  18. call_user_func_array('debug', array("_POST", $_POST)); 
  19. ?>

Tags: call_user_func call_user_func_array

分享到: