How to use Call_user_func dynamic call method in PHP

Source: Internet
Author: User

In PHP, you can use Call_user_func to make dynamic calls to methods, and to invoke normal functions, class methods, and class methods with parameters dynamically.
1. Define a common function getcurrentdate, which is used to get today's date.
The parameter on the Call_user_func band is the name of the function to be called
Fucntion Getcurrentdate () {
Echo ' Getcurrentdate: '. Date (' y-m-d ');
}
Call_user_func (' getcurrentdate ');


The program automatically executes the Getcurrentdate function and obtains the desired result
Getcurrentdate:2016-04-13


2. Define a class Cls53 and class method gettitle,call_user_func the input parameter becomes an array, the first element of the array is the object name, the second element is the class method name.
Class cls53{
Public Function GetTitle () {
Echo ' title ';
}
}


$cls = new Cls53 ();
Call_user_func (Array ($cls, ' getTitle '));


The program automatically calls the object CLS method GetTitle and obtains the desired result
Title


3. A method with parameters can also be called, at which time the GetTitle method is changed to GetTitle ($title).
When called, the second argument is the one that needs to be passed to the method
Class cls53{
Public Function GetTitle ($title) {
echo $title;
}
}


$cls = new Cls53 ();
Call_user_func (Array ($cls, ' getTitle '), ' abc ');


The incoming parameter is ABC, which results in the desired result:
Abc

How to use Call_user_func dynamic call method in PHP

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.