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

前端 未结 8 1358
囚心锁ツ
囚心锁ツ 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:50

    Closures:

    MDN has the best explanation IMO:

    A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.

    i.e. A closure is a function with access to the variables which are in the parent scope. A closure allows us to conveniently create functions on the fly since in some situations a functions is only needed in one place (callbacks, callable arguments).

    Example:

    $arr = [1,2,3,3];
    $outersScopeNr = 2;
    
    // The second arg in array_filter is a closure
    // It would be inconvenient to have this function in global namespace
    // The use keyword lets us access a variable in an outer scope
    $newArr = array_filter($arr, function ($el) use ($outersScopeNr) {
        return $el === 3 || $el === $outersScopeNr;
    });
    
    var_dump($newArr);
    // array (size=3)
    //  1 => int 2
    //  2 => int 3
    //  3 => int 3
    

提交回复
热议问题