php函数call_user_func跟call_user_func_array详解

WBOY
Release: 2016-06-13 13:14:02
Original
828 people have browsed it

php函数call_user_func和call_user_func_array详解

call_user_func函数类似于一种特别的调用函数的方法,使用方法如下:?
function a($b,$c)?
{
echo $b;
echo $c;
}
call_user_func('a', "111","222");
call_user_func('a', "333","444");
//显示 111 222 333 444
?>

调用类内部的方法比较奇怪,居然用的是array,不知道开发者是如何考虑的,当然省去了new,也是满有新意的:
class a {
function b($c)?
{
echo $c;
}
}
call_user_func(array("a", "b"),"111");
//显示 111
?>

call_user_func_array函数和call_user_func很相似,只不过是换了一种方式传递了参数,让参数的结构更清晰:
function a($b, $c)?
{
echo $b;
echo $c;

}
call_user_func_array('a', array("111", "222"));
//显示 111 222
?>

call_user_func_array函数也可以调用类内部的方法的

Class ClassA
{

function bc($b, $c) {
???? $bc = $b + $c;
echo $bc;
}
}
call_user_func_array(array('ClassA','bc'), array("111", "222"));

//显示 333
?>

call_user_func函数和call_user_func_array函数都支持引用,这让他们和普通的函数调用更趋于功能一致:
function a(&$b)
{
$b++;
}
$c = 0;
call_user_func('a', &$c);
echo $c;//显示 1
call_user_func_array('a', array(&$c));
echo $c;//显示 2

?

?

php之call_user_func_array的简易用法

今天在群里面,有个叫lewis的在问call_user_func_array的用法,因为之前一直没有用过,也不能说什么,于是看一下手册,发现是这么写的:

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5)

call_user_func_array -- Call a user function given with an array of parameters

Description

mixed?call_user_func_array?( callback function, array param_arr )

Call a user defined function given by?function, with the parameters in?param_arr.?
然后还有一个例子:

?

相信看了例子之后应该有点明白了吧?
我自己是这么理解这个函数的,如果说的不对,还望各位高手不要耻笑:
???? 该函数真正的用法有点类似于函数重载,因为他的第一个参数是字符型的,也就是函数的名称,第二个参数是数组,我们可以当成该函数的各个参数,而事实上也就是这么用的,如果你看过我的前一篇文章:PHP的伪重载?,或许你能够理解,正是因为这个函数的存在,我发现函数重载也可以这样运用:

function otest1 ($a)
 {
    echo( '一个参数' );
}

function otest2 ( $a, $b)
{
     echo( '二个参数' );
  }

  function otest3 ( $a ,$b,$c)
  {
      echo( '三个啦' );
  }

 function otest ()
  {
     $args = func_get_args();
     $num = func_num_args();
      call_user_func_array( 'otest'.$num, $args   );
   }

  otest(1,2);
Copy after login
?

?

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!