我们都知道,在PHP5中并没有真正的支持重载。借助的魔术方法__call()和call_user_func_array函数可以实现伪重载。
下面来和大家分享一下这个call_user_func_array和call_user_func函数的用法,另外附赠func_get_args()函数和func_num_args()函数
官方文档:http://cn2.php.net/call_user_func_array
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");
?>
重载类实例:
class Test {
public function __call($fun, $argps) {
if (method_exists($this, $fun.count($argps))) {
return call_user_func_array(array(&$this, $fun.count($argps)), $argps);
} else {
throw new Exception('调用了未知方法:'.get_class($this).'->'.$fun); //不存在的方法
}
}
//一个参数的方法
public function fun1($a) {
echo "你在调用一个参数的方法,参数为:".$a;
}
//两个参数的方法
public function fun2($a, $b) {
echo "你在调用两个参数的方法,参数为:".$a."和".$b;
}
}
$test = new Test();
$test->fun("a"); //输出 你在调用一个参数的方法,参数为:a
$test->fun("a","b"); //输出 你在调用两个参数的方法,参数为:a和b
$test->fun("a","b","c"); //输出 Fatal error: Uncaught exception 'Exception' with message '调用了未知方法:Test->fun'
大家好好运行看看就能明白了
(责任编辑:ken)