Home >php教程 >php手册 >php 动态执行带有参数的类方法

php 动态执行带有参数的类方法

WBOY
WBOYOriginal
2016-06-13 12:24:221008browse

官方手册给出了以下范例:

复制代码 代码如下:


// 使用了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.");
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn