<?php
class AnotherTestClass {
public static function printMe() {
print "This is Test2::printSelf.\n";
}
public function doSomething() {
print "This is Test2::doSomething.\n";
}
public function doSomethingWithArgs($arg1, $arg2) {
print 'This is Test2::doSomethingWithArgs with ($arg1 = '.$arg1.' and $arg2 = '.$arg2.").\n";
}
}
$testObj = new AnotherTestClass();
call_user_func(array("AnotherTestClass", "printMe"));
call_user_func(array($testObj, "doSomething"));
call_user_func(array($testObj, "doSomethingWithArgs"),"hello","world");
call_user_func_array(array($testObj, "doSomethingWithArgs"),array("hello2","world2"));
运行结果如下:
bogon:TestPhp$ php call_user_func_test.php
This is Test2::printSelf.
This is Test2::doSomething.
This is Test2::doSomethingWithArgs with ($arg1 = hello and $arg2 = world).
This is Test2::doSomethingWithArgs with ($arg1 = hello2 and $arg2 = world2). 2. func_get_args、func_num_args和func_get_args:
这三个函数的共同特征是都很自定义函数参数相关,而且均只能在函数内使用,比较适用于可变参数的自定义函数。他们的函数原型和简要说明如下: int func_num_args (void) 获取当前函数的参数数量。 array func_get_args (void) 以数组的形式返回当前函数的所有参数。 mixed func_get_arg (int $arg_num) 返回当前函数指定位置的参数,其中0表示第一个参数。
<?php
function myTest() {
$numOfArgs = func_num_args();
$args = func_get_args();
print "The number of args in myTest is ".$numOfArgs."\n";
for ($i = 0; $i < $numOfArgs; $i++) {
print "The {$i}th arg is ".func_get_arg($i)."\n";
}
print "\n-------------------------------------------\n";
foreach ($args as $key => $arg) {
print "$arg\n";
}
}
myTest('hello','world','123456');
运行结果如下:
Stephens-Air:TestPhp$ php class_exist_test.php
The number of args in myTest is 3
The 0th arg is hello
The 1th arg is world
The 2th arg is 123456
-------------------------------------------
hello
world
123456 3. function_exists和register_shutdown_function:
函数原型和简要说明如下: