In PHP, what is a closure and why does it use the "use" identifier? In PHP, what is a closure and why does it use the "use" identifier? php php

In PHP, what is a closure and why does it use the "use" identifier?


A simpler answer.

function ($quantity) use ($tax, &$total) { .. };

  1. The closure is a function assigned to a variable, so you can pass it around
  2. A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword:
  3. use allows you to access (use) the succeeding variables inside the closure.
  4. use is early binding. That means the variable values are COPIED upon DEFINING the closure. So modifying $tax inside the closure has no external effect, unless it is a pointer, like an object is.
  5. You can pass in variables as pointers like in case of &$total. This way, modifying the value of $total DOES HAVE an external effect, the original variable's value changes.
  6. Variables defined inside the closure are not accessible from outside the closure either.
  7. Closures and functions have the same speed. Yes, you can use them all over your scripts.

As @Mytskine pointed out probably the best in-depth explanation is the RFC for closures. (Upvote him for this.)


This is how PHP expresses a closure. This is not evil at all and in fact it is quite powerful and useful.

Basically what this means is that you are allowing the anonymous function to "capture" local variables (in this case, $tax and a reference to $total) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.


The function () use () {} is like closure for PHP.

Without use, function cannot access parent scope variable

$s = "hello";$f = function () {    echo $s;};$f(); // Notice: Undefined variable: s
$s = "hello";$f = function () use ($s) {    echo $s;};$f(); // hello

The use variable's value is from when the function is defined, not when called

$s = "hello";$f = function () use ($s) {    echo $s;};$s = "how are you?";$f(); // hello

use variable by-reference with &

$s = "hello";$f = function () use (&$s) {    echo $s;};$s = "how are you?";$f(); // how are you?