Several uses of PHP callback function

Source: Internet
Author: User
Tags types of functions

Article Source: http://www.cnitblog.com/CoffeeCat/archive/2009/04/21/56541.html

Preface


Recently in the development of a PHP system, in order to improve the scalability of the system, I would like to add a JavaScript-like event processing mechanism, for example: I want to be added to a piece of news, I want to record the log, in JavaScript-like code, it should be written like this: function Fncallback ($news)
{
Logs $news information to the log
Writelog ($news->gettitle (). ' has been added successfully! ');
}

$newsEventManager->addeventlistener (' Add ', fncallback);

Where the Fncallback function is a callback function, AddEventListener represents the Add event that listens for Newseventmanager. When a news is add, the system calls the Fncallback function, which completes the Writelog action.

However, the function passing method in PHP is very different from JavaScript. In JavaScript, a function is also an object, which can be easily passed as a parameter, but not PHP. $newsEventManager->addeventlistener (' Add ', fncallback);
The fncallback in this line of code looks like a handle to that function, but in essence it is a string, not the function we want.

In order to implement our event model, it is necessary to study the implementation method of PHP callback function.



callback for global function

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

Sample code function Fncallback ($msg 1, $msg 2)
{
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;
}
$fnName = "Fncallback";
$params = Array (' Hello ', ' world ');
Call_user_func_array ($fnName, $params);
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.


The effect is as follows:




callback for static methods of the class

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 ';
$fnName = "Fncallback";
$params = Array (' Hello ', ' world ');
Call_user_func_array (Array ($className, $fnName), $params);

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

Operation Result:


(In fact, the result of the 1th method is the same ^_^)


Continue to study

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);
Run results


And the previous results are the same ...


Now I'm adding a bit of property to this class and referencing it in the method

Class MyClass
{
Private $name = ' abc ';
Public Function Fncallback ($msg 1, $msg 2)
{
Echo ' Object name: '. $this->name;
echo "<br/>\n";
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);
Run results


A parsing error occurred stating that $this did not appear in the object environment, indicating that the method could not be called with a class, but instead called with an object. So let's modify the code to create an object:
Class MyClass
{
Public Function Fncallback ($msg 1, $msg 2)
{
Echo ' MSG1: '. $msg 1;
echo "<br/>\n";
Echo ' MSG2: '. $msg 2;
}
}

$myobj = new MyClass ();
$className = ' myobj ';
$fnName = "Fncallback";
$params = Array (' Hello ', ' world ');
Call_user_func_array (Array ($className, $fnName), $params);
Operation Result:



It is suggested that the 1th argument of Call_user_func_array is illegal, that is, the call failed. It seems that we can not use the Call_user_func_array method to callback the method of an object, then how to implement the callback of the object method?


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 ();
Success, output



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 ');

function Anonymous ()
{
Global $myobj;
Global $fnName;
Global $params;
$myobj-$fnName ($params [0], $params [1]);
}
Anonymous ();
Successfully, you can see that the properties of the object name are also lost.



Then I use Create_function to create this anonymous function, and params[0],params[1 in the code should be dynamically generated, with the following code:

$strParams = ";
$strCode = ' Global $myobj, Global $fnName, Global $params, $myobj-$fnName (';
for ($i = 0; $i < count ($params); $i + +)
{
$strParams. = (' $params ['. $i. '] ');
if ($i! = Count ($params)-1)
{
$strParams. = ', ';
}
}
$strCode = $strCode. $strParams. ");
$anonymous = Create_function (' ', $strCode);
$anonymous ();

This code can define an anonymous function, save it in the $anonymous variable, and finally call the $anonymous to implement the callback for the method,




implementation of PHP event Model (Observer pattern)


At this point, PHP 3 common types of functions (global functions, class static functions, methods of objects) can be recalled, you can achieve the beginning of the story of the event model:)

The event model mimics Firefox's JavaScript implementation, with 3 methods, namely

AddEventListener: Registering a response callback function on an event
RemoveEventListener: Deleting a response callback function on an event
Fire: Triggers an event that loops through all the callback functions that respond to this event

However, because the 2nd and 3rd methods need to pass the context (that is, the class name and the object name), AddEventListener and RemoveEventListener should have 3 parameters, which I have designed:

function AddEventListener ($evtName, $handler, $scope = null)
The 1th parameter represents the event name, the string type
The 2nd parameter represents the callback function name, the string type
The 3rd parameter, $scope, is the context, a total of 3 types, NULL means that the passed-in handler function is a global function, and the string type indicates that the passed-in handler function is a static function of the scope class, and the object type indicates that the scope passed in is an object, The handler function is a method of an object.

function Fire ($evtName, $params = null)
This method, will read out all the response Evtname handler, and then determine its corresponding scope, if it is null, then the 1th method in this article callback, if it is a string, the 2nd method of this article callback, if the object, then use the 3rd method of this article callback. In this way, a PHP event model can be implemented, and the callback function can be placed in an object.

Several uses of PHP callback function

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.