Heim  >  Artikel  >  php教程  >  php 动态执行带有参数的类方法

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

WBOY
WBOYOriginal
2016-06-13 12:24:22936Durchsuche

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

复制代码 代码如下:


// 使用了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