(转载)php之call_user_func_array的简易用法

(转载)http://www.cnitblog.com/neatstudio/archive/2006/07/21/13990.html

今天在群里面,有个叫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的伪重载 ,或许你能够理解,正是因为这个函数的存在,我发现函数重载也可以这样运用:

 1    /**
 2     * 例子写完后,本来认为完事了,结果遇到有人问call_user_func_array(),看了一下手册
 3     * 原来,我上面的那个test函数还可以精简成如下的例子,
 4     */
 5    function otest1 ($a)
 6    {
 7        echo'一个参数' );
 8    }
 9
10    function otest2 ( $a, $b)
11    {
12        echo'二个参数' );
13    }
14
15    function otest3 ( $a ,$b,$c)
16    {
17        echo'三个啦' );
18    }
19
20    function otest ()
21    {
22        $args = func_get_args();
23        $num = func_num_args();
24        call_user_func_array'otest'.$num, $args  );
25    }
26
27    otest(1,2);
28

看到不?而我最初的写法,在PHP的伪重载一文中有所提及,仅作参考。。。。

这些只是call_user_func_array的简易用法,在PHP4下测试过,而手册中还有一些将第一个参数当成数组来传入的例子,我在PHP4下是没有办法运行的,也许PHP5可以吧,但我不用PHP5的,也没有办法解释什么。谢谢各位

原文地址:https://www.cnblogs.com/Robotke1/p/3140210.html