What is the use of the PHP callback function?

Source: Internet
Author: User
Tags urlencode
As a variable to understand the easier, such as $a=function () {echo "AAA";}; $aa (); or function A () {}; Assign a value as a variable; $b = "a"; $b (); one is the anonymous function as a variable to call, and the other is the function name as a variable to call, this is the callback function commonly used way, simply speaking, this way to call the function is called the callback function

callback function callback

We all know that when the asynchronous request is often handled in JS, if you use a normal function, you may not be able to guarantee that the asynchronous request is complete. So there is the callback function, especially in the file processing and AJAX processing, the role of the callback function is very large.
function Call_user_func ()
Mixed Call_user_func (callable $callback [, Mixed $parameter [, mixed $ ...])

Return returns the value of a composite type, which is actually the value returned by the callback function

Callable $callback callback function can be a function name, can be an array, can be a string

Mixed $parameter parameters of the function, displayed in order

Here's an introduction to using Demo
DEMO1: Callback php function String form

<?php$data = Array ("name" = "Callback", "value" = "Test"), $rs 1 = http_build_query ($data);      Call the PHP function directly $rs2  = Call_user_func ("Http_build_query", $data);//Use the callback function echo $rs 1;  Name=callback&value=testecho "<br/>"; Echo $rs 2;  name=callback&value=test//It is important to note here that the parameter 1 must be a function that can be used by function_exists () to return true, here to remind Isset,empty,is_null The commonly used function is actually an operator. It cannot be counted as a function.

Demo2 callback PHP function function name variable form

<?php//Custom Function Myurldecode ($str) {    return UrlDecode ($STR);} $data = Array ("name" = "Callback", "value" = "genius"), $str  = Http_build_query ($data), $rs 1  = UrlDecode ($str );      UrlEncode encoded $RS2  = Call_user_func (Myurldecode, $STR); Echo $rs 1;  Name=callback&value= genius echo "<br/>"; Echo $rs 2;  Name=callback&value= Genius//Here we can see that the name of the function we use directly is also possible, without the need for a quoted string.?>

Demo3 callback class method array format

<?php class myclass{    Private $demo = "Test";    function Myurldecode ($str) {        return UrlDecode ($STR);    }    Static  function Myurlencode ($str) {        return UrlEncode ($STR);}    } $str = "? Query=/test/demo1"; $encode  = Call_user_func (Array (MyClass, "Myurlencode"), $str);//static method of using class directly URL encoding of a string is no longer a string or function name, but an array format, the first item represents the class name, and the second item represents the method name. The first item can be a reference address for a class, the second is a static method name $decode  = Call_user_func (Array ("MyClass", "Myurlencode"), $encode);//The same method of using classes, However, the normal method name is called. echo $encode;  %3fquery%3d%2ftest%2fdemo1echo "<br/>"; ? query=/test/demo1echo $decode;//Note the use of method names also has scope concepts, private protected and public, and typically callback class methods can only invoke methods of Publi and default scopes. At the same time, if it is a normal method, and the internal use of the $this variable, then the invocation is not successful. >

Demo4 Callback class method string format

<?phpclass myclass{    Private $demo = "Test";    function Myurldecode ($str) {        return UrlDecode ($STR);    }    Private Function MyUrldecode2 ($str) {    return UrlDecode ($STR);    }    Static  function Myurlencode ($str) {        return UrlEncode ($STR);}    } $str = "Query=/test/demo1";  $encode  = Call_user_func ("Myclass::myurlencode", $str);  $decode  = Call_user_func ("Myclass::myurldecode", $encode);  Echo $encode;  %3fquery%3d%2ftest%2fdemo1  echo "<br/>";  Echo $decode;  query=/test/demo1  $encode 2  = Call_user_func ("Myclass::myurlencode2", $str);  Var_dump ($encode 2);  null//If you use the string method directly, you must add:: As a split in the class and method name. Here we find that not static methods can also be used:: Make a call//a test is performed here, and the method that calls the private scope returns a null value indicating that there is a scope relationship?>

Demo5 callback object Method array format

<?phpclass myclass{    Private $demo = "Test";    function Myurldecode ($str) {        return UrlDecode ($STR)  . " -". $this->demo; Call internal this scope    }    static  function Myurlencode ($str) {        return UrlEncode ($STR);    }} $str = "? query=/ Test/demo1 "; $class =  New MyClass (), $encode  = Call_user_func (Array ($class, "Myurlencode"), $str); $decode  = Call_ User_func (Array ($class, "Myurldecode"), $STR); Echo $encode; %3fquery%3d%2ftest%2fdemo1 echo "<br/>"; Echo $decode; ? query=/test/demo1-test//Obviously, if you use an object as a callback function, internal private properties and methods can also be used, but the external method must be the default or public type//object array The first option must be an object? >

Sometimes we find that the parameters passed may not be fixed, then using Call_user_func () will bring a certain amount of trouble, this time you can use the Call_user_func_array () method, most of the use of the same way, Only the use of parameters is somewhat different.
function Call_user_func_array ()

Demo1 callback PHP function indeterminate parameter

<?php    $record 1 = array (            ' id ' = = 2135,    );    $record 2 = Array (        ' first_name ' = ' Sally ',    );    $record 3 = Array (        ' last_name ' = ' Jones ',    ); $return  = Array_merge ($record 1, $record 2, $record 3);// If the callback function is used, the following $return  = Call_user_func_array ("Array_merge", Array ($record 1, $record 2, $record 3));p Rint_r ($ return); Array ([id] = 2135 [first_name] = Sally [last_name] = Jones)///Some special functions allow you to have an invariant parameter, and if you also use it as a callback function, you can adjust it using this method. Use.? >

Tips1 How to determine if a callback function is possible
BOOL Is_callable (callable $name [, bool $syntax _only = False [, string & $callable _name]])

Name
The callback function to check.
Syntax_only
If set to TRUE, this function simply verifies that name may be a function or method.
Callable_name
Accept the "callable name".
Return
Returns TRUE if name is callable, otherwise FALSE

<?php//is_callable (); $bool = is_callable (UrlEncode);  True$bool = is_callable (urlencode,false);  True$bool = is_callable (urlencode,true);  True$bool = is_callable ("UrlEncode", False, $callable _name1);//String urlencode$bool = Is_callable ("UrlDecode", True , $callable _name2); String UrlDecode returns true?> even if no callback function exists

TIPS2 gets the parameters of the function similar to the arguments in JS

<?php//refers to the non-client PHP script function sum ($first, $second) {$args = Func_get_args ();//Get list  //func_get_arg ($index) Gets the parameter of the specified position $len  = Func_num_args ();//Gets the length $sum = 0; foreach ($args as $key = = $val) {$sum + = (int) $val;} return $sum;} $rs = SUM (1,2,3,4,5); Var_dump ($RS);  int 15//Note: If you modify $first, $second variable in the SUM function and not reference the object variable, the?> is not modified.

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.