The principle of callback function and PHP example

Source: Internet
Author: User
Tags php example

Background: In a recent development project, the user should call the service first to start a series of query activities, think for a long time, with a colleague reminded, with a callback function can solve the problem. Here, the principle and implementation of the callback function under PHP are explained separately.


1 What is a callback

There is always a certain interface between software modules, which can be divided into three categories: synchronous invocation, callback and asynchronous invocation. A synchronous call is a blocking call that is returned when the caller waits for the execution to complete, a one-way invocation, or a two-way invocation pattern, that is, the callee invokes the interface when the interface is called, and the asynchronous invocation is a mechanism similar to a message or event, but it is called in the opposite direction. The service of an interface notifies the client (that is, the interface that invokes the client) when it receives a message or an event occurs. Callbacks are very closely related to asynchronous calls, and we typically use callbacks to register asynchronous messages and to implement notification of messages through asynchronous calls. Synchronous calls are the simplest of the three, and callbacks are often the basis of asynchronous invocations, so here we focus on the implementation of callback mechanisms in different software architectures.

For different types of languages (such as structured languages and object languages), platforms (Win32, JDK), or architectures (CORBA, DCOM, WebService), the interaction of customers and services requires a certain asynchronous notification mechanism, in addition to synchronous methods. Let the service party (or interface provider) in some cases be able to proactively notify customers, and callbacks are the most straightforward way to implement Asynchrony. For a general structured language, callbacks can be implemented using callback functions. A callback function is also a function or procedure, but it is a special function that is implemented by the caller themselves for use by the callee.
In object-oriented languages, callbacks are implemented through interfaces or abstract classes, and we make the class that implements the interface a callback class, and the object of the callback class becomes the callback object. For object languages that are compatible with process features such as C + + or Object Pascal, they provide not only the callback object, the callback method and other features, but also the callback function mechanism of the process language. The message mechanism of the Windows platform can also be seen as an application of callbacks, and we register message handlers (i.e. callback functions) through the interface provided by the system to achieve the purpose of receiving and processing messages. Because the Windows Platform API is built in C, we can assume that it is also a special case of a callback function. For the Distributed Component Agent system CORBA, there are many ways of asynchronous processing, such as callback, event Service, notification Service and so on. The Event Service and Notification service are standard services that CORBA uses to process asynchronous messages, and they are primarily responsible for processing, distributing, and maintaining messages. For some simple asynchronous processing, we can implement it through a callback mechanism.

2 How to implement the callback function of PHP


2.1 Callbacks for global functions

The meaning of the global function here is to directly use functions defined by the function, which is not contained in any object or class. Take a look at the following example
function Fncallback ($msg 1, $msg 2)
{
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;

}


$fnName = "fncallback";//Method name
$params = Array (' Hello ', ' world ');// value passed to parameter

Call_user_func_array ($fnName, $params);

Results:


Code Description:
The PHP built-in function Call_user_func_array is used here to make the call. Call_user_func_array has two parameters, the 1th parameter is a string representing the function name to invoke, and the 2nd parameter is an array representing the list of parameters, which in turn is passed to the function to be called.

Callback for static methods of class 2.2
What if we want the callback method, which is a static method of a class? We can still use PHP's built-in Call_user_func_array method to make calls, see example:
Example code:
Class MyClass
{
public static function Fncallback ($msg 1, $msg 2)
{
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;
}
}


$className = ' MyClass '; Class name
$fnName = "Fncallback";//Method name in class
$params = Array (' Hello ', ' world ');//value passed to parameter
Call_user_func_array (Array ($className, $fnName), $params);


Results:


Code Description:
This code is similar to the code of the 1th method, and we can implement the callback of the class's static method by passing the class name (MyClass) as the 1th parameter of the Call_user_func_array. Note that at this point the 1th parameter of Call_user_func_array is an array, the 1th element of the array is the class name, the second element is the name of the function to be called

What happens if I call a non-static method of a class in this way (that is, remove static)? Take a look at the following code
Class MyClass
{
Public Function Fncallback ($msg 1, $msg 2)
{
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;
}
}
$className = ' MyClass ';
$fnName = "Fncallback";
$params = Array (' Hello ', ' world ');
Call_user_func_array (Array ($className, $fnName), $params);
The end result is the same as the original.


2.3 Callback for the method of the object

I tried it first with the most primitive string invocation method, as follows:
Class MyClass
{
Private $name = ' abc ';
Public Function Fncallback ($msg 1 = ' default Msg1 ', $msg 2 = ' default MSG2 ')
{
Echo ' Object name: '. $this->name;
echo "<br/>\n";
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;
}
}
$myobj = new MyClass ();
$fnName = "Fncallback";
$params = Array (' Hello ', ' world ');
$myobj $fnName ();

Results:


The call was successful, but how to pass the parameter params to this method, if the params is passed directly into it, then it will be used as 1 parameters, how to take the params apart to pass in it? Check the PHP manual, found the Create_function function, this method can use a string to create an anonymous function, good, have ideas, you can create an anonymous function, in this anonymous function, call our callback function, and the parameters passed in.
I'll start by manually creating an anonymous function anonymous, in which the callback function is invoked using the method previously tried, as shown here:
Class MyClass
{
Private $name = ' abc ';
Public Function Fncallback ($msg 1 = ' default Msg1 ', $msg 2 = ' default MSG2 ')
{
Echo ' Object name: '. $this->name;
echo "<br/>\n";
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;
}
}
$myobj = new MyClass ();
$fnName = "Fncallback";
$params = Array (' Hello ', ' world ');
The construction of anonymous function
function Anonymous ()
{
Global $myobj;
Global $fnName;
Global $params;
$myobj-$fnName ($params [0], $params [1]);
}
Anonymous ();

It worked. The effect is as follows:

Reference documents:
http://myceo.blog.51cto.com/2340655/725411/
Http://blog.chinaunix.net/uid-20684384-id-1895266.html
http://segmentfault.com/a/1190000002901770

Http://www.abc3210.com/2012/phper_07/php-callback.shtml

Thank you for all the references and bloggers!

Copyright: Hello, very happy to meet you on the CSDN! Hope to make friends with you!

The principle of callback function and PHP example

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.