详解call_user_func函数和call_user_func_array函数
	
今天在shopnc中再次看到了php中的call_user_func_array()这个函数,在网上搜索到了这个函数的用法(PS:虽然php手册中有关于这个函数的介绍,但是看了介绍还是不明白,也不知道是我的理解能力不行还是文档说明的太模糊了,不信你自己去看看:http://cn2.php.net/call_user_func_array)
下面来和大家分享一下这个call_user_func_array和call_user_func函数的用法,另外附赠func_get_args()函数和func_num_args()函数,嘿嘿!!
call_user_func函数是当需要动态调用函数时,才使用的,这个函数有两种用法:
第一种是调用孤独的函数:
<!--?
function funa($b,$c)
{
echo $b;
echo $c;
}
call_user_func('funa', "111","222");
call_user_func('funa', "333","444");
//显示 111 222 333 444
//大家有没有发现,这个用法有点像javascript中的call方法,嘿嘿
?-->
第二种是调用类内部的函数:
<!--?
class a {
    function b()
    {
    $args = func_get_args();
        $num = func_num_args();
        print_r($args);
        echo $num;
    }
}
call_user_func(array("a", "b"),"111","222");
?-->
上面这个例子,自己运行一下看看结果是什么吧~嘿嘿~提示一下func_get_args()函数是获取传入到函数中的参数,返回一个数组,func_num_args()函数获取传入函数中的参数的个数。
下面再来看看
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
?–>
下面再看一个动态调用函数的例子:是从网上找来的:
<!--?
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("11");
otest("11","22");
otest("11","22","33");
?-->
	
本文发布于程序达人 ,转载请注明出处,谢谢合作
共同学习,写下你的评论
相关热点文章推荐
Spring Boot文档翻译【转】
Spring Boot报java.lang.IllegalArgumentException:Property 'sqlSessionFactory' or 'sqlSessionTemplate'
SpringBoot 2.0 报错: Failed to configure a DataSource: 'url' attribute is not specified and no embe...
UploadiFive Documentation (api 说明文档)
svn: 目录中的条目从本地编码转换到 UTF8 失败 解决办法
解决Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile办法
程序达人 - chengxudaren.com
一个帮助开发者成长的社区