(网址安全问题,请自行将方法中-替换为_)
在discuz代码和CodeIgniter等框架中经常看到这两个函数,今天查了下资料看了下这两个函数。
这两个函数主要是对函数的动态调用,下面是几个例子:
1、call-user-func()使用,第一个参数是方法名,后面的参数就是调用函数的参数。
call-user-func('test', 'a', 'b');
function test($a, $b){
echo 'a=', $a;
echo '<br>';
echo 'b=', $b;
}
call-user-func()也可以调用内部方法,但是方法需要时静态的:
call-user-func(array('TestClass','test'), '1');
class TestClass{
static function test($a){
echo 'a=', $a;
}
}
2、call-user-func-array()和call-user-func()的用法类似,只是可以传array参数:
call-user-func-array('array_test', array('a', 'b'));
function array_test($a, $b){
echo "a=", $a;
echo "b=", $b;
}
3、利用call-user-func-array()函数实现php中的伪重载:
// 动态调用,伪重载
otest('a');
otest('a', 'b');
otest('a', 'b', 'c');
function otest1($a){
echo "我是test1", '<br>';
}
function otest2($a, $b){
echo "我是test2", '<br>';
}
function otest3($a, $b, $c){
echo "我是test3", '<br>';
}
function otest(){
$args = func_get_args();
$num = func_num_args();
call-user-func-array('otest'.$num, $args);
}