当前位置:Gxlcms > PHP教程 > php学习之道:call_user_func跟call_user_func_array的用法

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

时间:2021-07-01 10:21:17 帮助过:5人阅读

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. ?>


调用类的内部方法:

Php代码 收藏代码

  1. class myclass {
  2. function say_hello($name)
  3. {
  4. echo "Hello!$name";
  5. }
  6. }
  7. $classname = "myclass";
  8. //调用类内部的函数需要使用数组方式 array(类名,方法名)
  9. call_user_func(array($classname, 'say_hello'), 'dain_sun');
  10. //print Hello! dain_sun
  11. ?>



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

call_user_func_array ( callback $function , array $param_arr )

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

Php代码 收藏代码

  1. function debug($var, $val)
  2. {
  3. echo "variable: $var
    value: $val
    "
    ;
  4. echo "
    "
    ;
  5. }
  6. $host = $_SERVER["SERVER_NAME"];
  7. $file = $_SERVER["PHP_SELF"];
  8. call_user_func_array('debug', array("host", $host));
  9. call_user_func_array('debug', array("file", $file));
  10. ?>



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

exmaple:

Php代码 收藏代码

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



注:call_user_func 函数和call_user_func_array函数都支持引用。

Php代码 收藏代码

  1. function increment(&$var)
  2. {
  3. $var++;
  4. }
  5. $a = 0;
  6. call_user_func('increment', $a);
  7. echo $a; // 0
  8. call_user_func_array('increment', array(&$a)); // You can use this instead
  9. echo $a; // 1
  10. ?>

人气教程排行