Search code examples
phpsyntaxanonymous-function

PHP use() function for scope?


I have seen code like this:

function($cfg) use ($connections) {}

but php.net doesn't seem to mention that function. I'm guessing it's related to scope, but how?


Solution

  • use is not a function, it's part of the Closure syntax. It simply makes the specified variables of the outer scope available inside the closure.

    $foo = 42;
    
    $bar = function () {
        // can't access $foo in here
        echo $foo; // undefined variable
    };
    
    $baz = function () use ($foo) {
        // $foo is made available in here by use()
        echo $foo; // 42
    }
    

    For example:

    $array = array('foo', 'bar', 'baz');
    $prefix = uniqid();
    
    $array = array_map(function ($elem) use ($prefix) {
        return $prefix . $elem;
    }, $array);
    
    // $array = array('4b3403665fea6foo', '4b3403665fea6bar', '4b3403665fea6baz');