Javascript closures vs PHP closures, what's the difference?

后端 未结 3 819
遥遥无期
遥遥无期 2021-01-29 20:57

What are the differences between closures in JS and closures in PHP? Do they pretty much work the same way? Are there any caveats to be aware of when writing closures in PHP? <

3条回答
  •  没有蜡笔的小新
    2021-01-29 21:36

    They do pretty much work the same way. Here's more information about the PHP implementation: http://php.net/manual/en/functions.anonymous.php

    You can use a closure (in PHP called 'anonymous function') as a callback:

    // return array of ids
    return array_map( function( $a ) { return $a['item_id']; }, $items_arr );
    

    and assign it to a variable:

    $greet = function( $string ) { echo 'Hello ' . $string; }; // note the ; !
    echo $greet('Rijk'); // "Hello Rijk"
    

    Furthermore, anonymous function 'inherit' the scope in which they were defined - just as the JS implementation, with one gotcha: you have to list all variables you want to inherit in a use():

    function normalFunction( $parameter ) {
        $anonymous = function() use( $parameter ) { /* ... */ };
    }
    

    and as a reference if you want to modify the orignal variable.

    function normalFunction( $parameter ) {
        $anonymous = function() use( &$parameter ) { $parameter ++ };
        $anonymous();
        $parameter; // will be + 1
    }
    

提交回复
热议问题