Closures in PHP… what, precisely, are they and when would you need to use them?

前端 未结 8 1330
囚心锁ツ
囚心锁ツ 2021-01-29 20:50

So I\'m programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I

8条回答
  •  时光说笑
    2021-01-29 21:40

    PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The RFC for closures give a good example:

    function replace_spaces ($text) {
        $replacement = function ($matches) {
            return str_replace ($matches[1], ' ', ' ').' ';
        };
        return preg_replace_callback ('/( +) /', $replacement, $text);
    }
    

    This lets you define the replacement function locally inside replace_spaces(), so that it's not:
    1) Cluttering up the global namespace
    2) Making people three years down the line wonder why there's a function defined globally that's only used inside one other function

    It keeps things organized. Notice how the function itself has no name, it simply is defined and assigned as a reference to $replacement.

    But remember, you have to wait for PHP 5.3 :)

    You can also access variables outside it's scope into a closure using the keyword use. Consider this example.

    // Set a multiplier  
     $multiplier = 3;
    
    // Create a list of numbers  
     $numbers = array(1,2,3,4);
    
    // Use array_walk to iterate  
     // through the list and multiply  
     array_walk($numbers, function($number) use($multiplier){  
     echo $number * $multiplier;  
     }); 
    

    An excellent explanation is given here What are php lambdas and closures

提交回复
热议问题