How to use closures in PHP?

Closures:

A closure is an anonymous function that can't access outside scope.

When defining an anonymous function as such, you're creating a "namespace" for that function. It currently only has access to that namespace.

$externalVariable = "Hello";

$secondExternalVariable = "Foo";

$myFunction = function() {

    var_dump($externalVariable, $secondExternalVariable); // returns two error notice, since the variables aren´t defined

}

It doesn't have access to any external variables. To grant this permission for this namespace to access external variables, you need to introduce it via closures (use()).

code:

$myFunction = function() use($externalVariable, $secondExternalVariable) {

    var_dump($externalVariable, $secondExternalVariable); // Hello Foo

}


This is heavily attributed to PHP's tight variable scoping - If a variable isn't defined within the scope, or isn't brought in with global then it does not exist.

In PHP, closures use an early-binding approach. This means that variables passed to the closure's namespace using use keyword will have the same values when the closure was defined.

To change this behavior you should pass the variable by-reference.

code:

$rate = .05;

// Exports variable to closure's scope

$calculateTax = function ($value) use ($rate) {

    return $value * $rate;

};

$rate = .1;

print $calculateTax(100); // 5

Default arguments are not implicitly required when defining anonymous functions with/without closures.

code:

$message = 'Hi, How are you?';

$yell = function() use($message) {

    echo strtoupper($message);

};

$yell(); // returns: HI, HOW ARE YOU?

I hope this article will help you the information about closures in PHP.

Thanks.

Tagged:
Sign In or Register to comment.