Home  >  Article  >  Backend Development  >  php学习之道:call_user_func跟call_user_func_array的用法

php学习之道:call_user_func跟call_user_func_array的用法

WBOY
WBOYOriginal
2016-06-13 12:01:21970browse

php学习之道:call_user_func和call_user_func_array的用法

call_user_func callback $function [, mixed $parameter [, mixed $... ]] ) 

调用第一个参数所提供的用户自定义的函数。
返回值:返回调用函数的结果,或FALSE。

example 

Php代码  收藏代码
  1. function eat($fruit//参数可以为多个  
  2. {  
  3.      echo "You want to eat $fruit, no problem";  
  4. }  
  5. call_user_func('eat'"apple"); //print: You want to eat apple, no problem;  
  6. call_user_func('eat'"orange"); //print: You want to eat orange,no problem;  
  7. ?>  
 <span style="color:rgb(0,0,187)"></span>


调用类的内部方法: 

Php代码  收藏代码
  1. class myclass {  
  2.      function say_hello($name)  
  3.      {  
  4.          echo "Hello!$name";  
  5.      }  
  6. }  
  7.   
  8. $classname = "myclass";  
  9.   
  10. //调用类内部的函数需要使用数组方式 array(类名,方法名)  
  11. call_user_func(array($classname'say_hello'), 'dain_sun');  
  12.   
  13. //print Hello! dain_sun  
  14.   
  15. ?>  
 <span style="color:rgb(0,0,187)"><br><br></span>

call_user_func_array 函数和 call_user_func 很相似,只是 使 用了数组 的传递参数形式,让参数的结构更清晰: 

call_user_func_array callback $function array $param_arr ) 

调用用户定义的函数,参数为数组形式。
返回值:返回调用函数的结果,或FALSE。

Php代码  收藏代码
  1.   
  2. function debug($var$val)  
  3. {  
  4.      echo "variable: $var 
     value: $val 
    "
    ;  
  5.      echo "
    "
    ;  
  6. }  
  7.   
  8.   
  9. $host = $_SERVER["SERVER_NAME"];  
  10. $file = $_SERVER["PHP_SELF"];  
  11.   
  12. call_user_func_array('debug'array("host"$host));  
  13. call_user_func_array('debug'array("file"$file));  
  14.   
  15.   
  16. ?>  
 



调用类的内部方法和 call_user_func 函数的调用方式一样,都是使用了数组的形式来调用。 

exmaple:

Php代码  收藏代码
  1.   
  2. class test  
  3. {  
  4.       function debug($var$val)  
  5.       {  
  6.           echo "variable: $var 
     value: $val 
    "
    ;  
  7.           echo "
    "
    ;  
  8.       }  
  9. }  
  10.   
  11. $host = $_SERVER["SERVER_NAME"];  
  12. $file = $_SERVER["PHP_SELF"];  
  13.   
  14. call_user_func_array(array('test''debug'), array("host"$host));  
  15. call_user_func_array(array('test''debug'), array("file"$file));  
  16.   
  17. ?>  
 

<span style="color:rgb(0,0,187)"><strong><br><span style="color:rgb(255,0,0)"><br></span></strong></span>注:call_user_func 函数和call_user_func_array函数都支持引用。 

Php代码  收藏代码
  1. function increment(&$var)  
  2. {  
  3.     $var++;  
  4. }  
  5.   
  6. $a = 0;  
  7. call_user_func('increment'$a);  
  8. echo $a// 0  
  9.   
  10. call_user_func_array('increment'array(&$a)); // You can use this instead  
  11. echo $a// 1  
  12. ?>  
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn