官方手册给出了以下范例:
// 使用了NameSpace的例子
namespace Foobar;
class Foo {
static public function test() {
print "Hello world!\n";
}
}
call_user_func(__NAMESPACE__ .'\Foo::test'); // As of PHP 5.3.0
// Hello world!
call_user_func(array(__NAMESPACE__ .'\Foo', 'test')); // As of PHP 5.3.0
// Hello world!
?>
// 直接调用方法的例子
class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}
$classname = "myclass";
call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello'); // As of 5.2.3
?>
那么,如果是普通的方法,而且,方法带有参数该怎么办? 以下是笔者写的一个小例子,供参考:
// 执行带有参数的类
class Loveapple{
public function sayHello($a, $b){
echo "Hello:".$a.". ".$b."\n";
}
}
$obj = new Loveapple();
//执行结果 Hello:loveapple. Using instance.
call_user_func(array($obj, "sayHello"), "loveapple", "Using instance.");
//执行结果 Hello:loveapple. Using class name.
call_user_func(array("Loveapple", "sayHello"), "loveapple", "Using class name.");
?>
Stellungnahme:Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn