Home > php教程 > php手册 > body text

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

PHPz
Release: 2018-09-30 17:08:48
forward
1089 people have browsed it

PHP中,在事先知道类和类的方法名称,使用call_user_func函数可以做动态执行。

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

代码如下:

<?php 
// 使用了NameSpace的例子 
namespace Foobar; 
class Foo { 
static public function test() { 
print "Hello world!\n"; 
} 
} 
call_user_func(__NAMESPACE__ .&#39;\Foo::test&#39;); // As of PHP 5.3.0 
// Hello world! 
call_user_func(array(__NAMESPACE__ .&#39;\Foo&#39;, &#39;test&#39;)); // As of PHP 5.3.0 
// Hello world! 
?>
Copy after login

代码如下:

<?php 
// 直接调用方法的例子 
class myclass { 
static function say_hello() 
{ 
echo "Hello!\n"; 
} 
} 
$classname = "myclass"; 
call_user_func(array($classname, &#39;say_hello&#39;)); 
call_user_func($classname .&#39;::say_hello&#39;); // As of 5.2.3 
?>
Copy after login

那么,如果是普通的方法,而且,方法带有参数该怎么办?

以下是笔者写的一个小例子,供参考:

代码如下:

<?php 
// 执行带有参数的类 
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."); 
?>
Copy after login

更多相关教程请访问 php编程从入门到精通全套视频教程

Related labels:
php
source:jb51.net
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!