Home > Backend Development > PHP Tutorial > PHP dynamically executes class methods with parameters_PHP tutorial

PHP dynamically executes class methods with parameters_PHP tutorial

WBOY
Release: 2016-07-21 15:47:01
Original
851 people have browsed it

The official manual gives the following example:

Copy code The code is as follows:

// Use Example of 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!
?>

Copy code The code is as follows:

// Example of direct method calling
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
?>

So, what if it is an ordinary method and the method has parameters?
The following is a small example written by the author for reference:
Copy the code The code is as follows:

//Execute the class with parameters
class Loveapple{
public function sayHello($a, $b){
echo "Hello:".$a.". " .$b."n";

}
}
$obj = new Loveapple();
//Execution result Hello: loveapple. Using instance.
call_user_func(array ($obj, "sayHello"), "loveapple", "Using instance.");
//Execution result Hello:loveapple. Using class name.
call_user_func(array("Loveapple", "sayHello") , "loveapple", "Using class name.");
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320023.htmlTechArticleThe official manual gives the following example: Copy the code as follows: ?php // Example using NameSpace namespace Foobar ; class Foo { static public function test() { print "Hello world!...
source:php.cn
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template