UCenter源代码里有一个函数call_user_func,开始以为是自己定义的函数,结果到处都找不到。后来才知道call_user_func是PHP的内置函数,该函数允许用户调用直接写的函数并传入一定的参数,下面总结下这个函数的使用方法。
call_user_func函数类似于一种特别的调用函数的方法,使用方法如下:
<?php function nowamagic($a,$b) { echo $a; echo $b; } call_user_func('nowamagic', "111","222"); call_user_func('nowamagic', "333","444"); //显示 111 222 333 444 ?>
调用类内部的方法比较奇怪,居然用的是array,不知道开发者是如何考虑的,当然省去了new,也挺有新意的:
<?php class a { function b($c) { echo $c; } } call_user_func(array("a", "b"),"111"); //显示 111 ?>
call_user_func_array函数和call_user_func很相似,只不过是换了一种方式传递了参数,让参数的结构更清晰:
<?php function a($b, $c) { echo $b; echo $c; } call_user_func_array('a', array("111", "222")); //显示 111 222 ?>
call_user_func_array函数也可以调用类内部的方法的:
<?php 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函数都支持引用,这让他们和普通的函数调用更趋于功能一致:
<?php function a($b) { $b++; } $c = 0; call_user_func('a', $c); echo $c;//显示 1 call_user_func_array('a', array($c)); echo $c;//显示 2 ?>
另外,call_user_func函数和call_user_func_array函数都支持引用。
<?php function increment(&$var) { $var++; } $a = 0; call_user_func('increment', $a); echo $a; // 0 call_user_func_array('increment', array(&$a)); // You can use this instead echo $a; // 1 ?>
延伸阅读
此文章所在专题列表如下:
- PHP函数补完:get_magic_quotes_gpc()
- PHP函数补完:error_reporting()
- PHP函数补完:preg_match()
- PHP函数补完:urlencode()
- PHP函数补完:array_multisort()
- PHP函数补完:array_splice()
- PHP函数补完:isset()
- PHP函数补完:getenv()
- PHP函数补完:header()
- PHP函数补完:mysql_num_rows()
- PHP函数补完:list()
- PHP函数补完:mysql_query()
- PHP函数补完:mysql_fetch_array()
- PHP函数补完:number_format()
- PHP函数补完:explode()
- PHP函数补完:call_user_func()
- PHP函数补完:ImageCopyResamples()
- PHP函数补完:import_request_variables()
- PHP函数补完:parse_url()
- PHP函数补完:移除HTML标签strip_tags()
- PHP函数补完:输出数组结构与内容var_dump()
- PHP函数补完:var_export()
- PHP函数补完:判断变量是否为数字is_numeric()
- PHP函数补完:session_name()
- PHP函数补完:session_id()
- PHP函数补完:nl2br()与nl2p()函数
- PHP函数补完:shuffle()取数组若干个随机元素
- PHP函数补完:http_build_query()构造URL字符串
- PHP函数补完:stream_context_create()模拟POST/GET
本文地址:http://www.nowamagic.net/librarys/veda/detail/1509,欢迎访问原出处。
大家都在看