search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the usage of callback function of PHP custom function

Detailed explanation of the usage of callback function of PHP custom function

Jun 26, 2017 am 11:01 AM
phpfunctionusagecustomizeDetailed explanation

I am developing a PHP system recently. In order to improve the scalability of the system, I want to add an event processing mechanism similar to Javascript to the system. For example: I want to add a message to the system. After being added, I want to record the log. Using code similar to Javascript, it should be written like this:

function fnCallBack( $news )
{
     //将$news的信息记录到日志中
    writeLog( $news->getTitle().' has been added successfully!');
}
$newsEventManager->addEventListener( 'add' , fnCallBack );

Among them, the fnCallBack function is the callback function, and addEventListener means listening for the add event of newsEventManager. . When a news article is added, the system will call the fnCallBack function to complete the writeLog action.

However, the function transfer method in PHP is very different from that in Javascript. In Javascript, functions are also objects, and they can be easily passed as parameters, but not in PHP.

$newsEventManager->addEventListener( 'add' , fnCallBack );

The fnCallBack in the above line of code looks like the handle of that function, but in fact it is a string and not the function we want.

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

1. Callback of global function

The global function here means a function defined directly using function. It is not included in any object or class. Please see the example below

Sample code:

function fnCallBack( $msg1 , $msg2 )
{
    echo 'msg1:'.$msg1;
    echo "<br />\n";
    echo &#39;msg2:&#39;.$msg2;
}
$fnName = "fnCallBack";
$params = array( &#39;hello&#39; , &#39;world&#39; );
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 first parameter is a string, indicating the name of the function to be called. The second parameter is an array, indicating the parameter list, which will be passed to the function to be called in order.

2. Callback of static methods of a class

What should we do if the method we want to callback is a static method of a class? ? We can still use PHP's built-in call_user_func_array method to make calls. Please see the example:
Sample code:

class MyClass
{
    public static function fnCallBack( $msg1 , $msg2 )
    {
        echo &#39;msg1:&#39;.$msg1;
        echo "<br />\n";
        echo &#39;msg2:&#39;.$msg2;
    }
}
$className = &#39;MyClass&#39;;
$fnName = "fnCallBack";
$params = array( &#39;hello&#39; , &#39;world&#39; );
call_user_func_array( array( $className , $fnName ) , $params );

Code description:
This code is very similar to the code of the first method. Similarly, if we pass the class name (MyClass) as the first parameter of call_user_func_array, we can implement the callback of the static method of the class. Note that the first parameter of call_user_func_array is an array at this time. The first element of the array is the class name, and the second element is the name of the function to be called.

3. Callback of the object's method
First try the calling method in the most original string form, as shown below:

class MyClass
{
    private $name = &#39;abc&#39;;
    public function fnCallBack( $msg1 = &#39;default msg1&#39; , $msg2 = &#39;default msg2&#39; )
    {
        echo &#39;object name:&#39;.$this->name;
        echo "<br />\n";
        echo &#39;msg1:&#39;.$msg1;
        echo "<br />\n";
        echo &#39;msg2:&#39;.$msg2;
    }
}
$myobj = new MyClass();
$fnName = "fnCallBack";
$params = array( &#39;hello&#39; , &#39;world&#39; );
$myobj->$fnName();

The call is successful, but how to pass the parameter params to this method? If the params are passed directly Pass it in, then it will be used as a parameter. How to split the params and pass it in?
I checked PHP manual and found the create_function function. This method can use strings to create an anonymous function. OK, I have an idea. I can create an anonymous function. , in this anonymous function, call our callback function and pass the parameters in.

First manually create an anonymous function anonymous. In this function, use the method I learned earlier to call the callback function, as shown below:

class MyClass
{
    private $name = &#39;abc&#39;;
    public function fnCallBack( $msg1 = &#39;default msg1&#39; , $msg2 = &#39;default msg2&#39; )
    {
        echo &#39;object name:&#39;.$this->name;
        echo "<br />\n";
        echo &#39;msg1:&#39;.$msg1;
        echo "<br />\n";
        echo &#39;msg2:&#39;.$msg2;
    }
}
$myobj = new MyClass();
$fnName = "fnCallBack";
$params = array( &#39;hello&#39; , &#39;world&#39; );
function anonymous()
{
    global $myobj;
    global $fnName;
    global $params;
    $myobj->$fnName( $params[0] , $params[1] );
}
anonymous();

Then, I use create_function to create This anonymous function, at the same time, params[0], params[1] in the code should be dynamically generated, the code is as follows:

$strParams = &#39;&#39;;
$strCode = &#39;global $myobj;global $fnName;global $params;$myobj->$fnName(&#39;;
for ( $i = 0 ; $i < count( $params ) ; $i ++ )
{
    $strParams .= ( &#39;$params[&#39;.$i.&#39;]&#39; );
    if ( $i != count( $params )-1 )
    {
        $strParams .= &#39;,&#39;;
    }
}
$strCode = $strCode.$strParams.");";
$anonymous = create_function( &#39;&#39; , $strCode);
$anonymous();

This code can define an anonymous function and save it in $ In the anonymous variable, $anonymous is finally called to implement the method callback.

The above is the detailed content of Detailed explanation of the usage of callback function of PHP custom function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.