Php dynamic execution of class methods with parameters _ PHP Tutorial

Source: Internet
Author: User
Php dynamically executes class methods with parameters. The official manual provides the following example: Copy the code as follows :? Example of using NameSpace in php namespaceFoobar; classFoo {staticpublicfunctiontest () {printHelloworld! The official manual provides the following examples:

The code is as follows:


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


The code is as follows:


// Example of directly calling a method
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 a common method and the method has parameters?
The following is a small example written by the author for your reference:

The code is as follows:


// Execute a 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 .");
?>

The pipeline code is as follows :? Php // NameSpace example namespace Foobar; class Foo {static public function test () {print "Hello world !...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.