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

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

WBOY
WBOYasal
2016-06-13 12:24:22936semak imbas

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

复制代码 代码如下:


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

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn