php 动态执行带有参数的类方法
Jun 13, 2016 pm 12:24 PM
官方手册给出了以下范例:
复制代码 代码如下:
// 使用了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.");
?>

Heißer Artikel

Hot-Tools-Tags

Heißer Artikel

Heiße Artikel -Tags

Notepad++7.3.1
Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1
Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6
Visuelle Webentwicklungstools

SublimeText3 Mac-Version
Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen

PHP 8.4 Installations- und Upgrade-Anleitung für Ubuntu und Debian

So richten Sie Visual Studio-Code (VS-Code) für die PHP-Entwicklung ein
