Bird
Raised Fist0
PHPprogramming~10 mins

Closures and variable binding with use in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Closures and variable binding with use
Define outer function
↓
Create closure with 'use'
↓
Closure captures variables by value
↓
Call closure
↓
Closure uses captured variables
↓
Return or output result
This flow shows how a closure captures variables from its surrounding scope using 'use', then uses them when called.
Execution Sample
PHP
<?php
$greeting = 'Hello';
$greeter = function($name) use ($greeting) {
    return "$greeting, $name!";
};
echo $greeter('Alice');
?>
This code creates a closure that captures $greeting by value and uses it to greet a given name.
Execution Table
StepActionVariable StateClosure BehaviorOutput
1Set $greeting = 'Hello'$greeting='Hello'N/AN/A
2Define closure $greeter capturing $greeting$greeting='Hello'Closure captures $greeting by value as 'Hello'N/A
3Call $greeter('Alice')$greeting='Hello'Closure uses captured $greeting='Hello' and parameter 'Alice'Returns 'Hello, Alice!'
4Echo closure result$greeting='Hello'N/AHello, Alice!
💡 Execution ends after printing the greeting message.
Variable Tracker
VariableStartAfter Closure DefinitionAfter Closure CallFinal
$greeting'Hello''Hello''Hello''Hello'
$nameN/AN/A'Alice'N/A
Key Moments - 2 Insights
Why does the closure still use the original value of $greeting even if $greeting changes later?
Because the closure captures $greeting by value at the time of definition (see step 2 in execution_table), later changes to $greeting do not affect the closure's copy.
What happens if we don't use 'use' to capture $greeting?
The closure won't have access to $greeting from the outer scope, causing an error or undefined variable inside the closure (not shown in this trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $greeting inside the closure when it is called?
A'Alice'
B'Hello'
Cnull
D'Goodbye'
💡 Hint
Check step 3 in the execution_table where the closure uses the captured $greeting.
At which step does the closure capture the variable $greeting?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the action 'Define closure' in the execution_table.
If $greeting was changed to 'Hi' after defining the closure but before calling it, what would the closure output?
A'Hi, Alice!'
BAn error
C'Hello, Alice!'
D', Alice!'
💡 Hint
Refer to variable_tracker and key_moments about capturing by value.
Concept Snapshot
Closure syntax: function(...) use ($var) { ... }
The 'use' keyword copies variables from outer scope by value.
Closure keeps original values even if outer variables change later.
Useful for creating functions with preset data.
Call closure like normal function with parameters.
Full Transcript
This example shows how PHP closures can capture variables from their surrounding scope using the 'use' keyword. First, we set a variable $greeting to 'Hello'. Then we define a closure $greeter that takes a name and uses $greeting from outside. The closure captures $greeting by value at definition time. When we call $greeter('Alice'), it returns 'Hello, Alice!'. Even if $greeting changes later, the closure still uses the original 'Hello' because it keeps its own copy. This is important to understand how closures bind variables in PHP.

Practice

(1/5)
1. What does the use keyword do in a PHP closure?
easy
A. It defines a new variable inside the closure.
B. It creates a global variable accessible everywhere.
C. It imports variables from the parent scope into the closure.
D. It calls the closure immediately.

Solution

  1. Step 1: Understand closure scope

    A closure is a function inside another function that can access variables from the outside only if explicitly told.
  2. Step 2: Role of use

    The use keyword brings variables from the parent scope into the closure's scope so the closure can use them.
  3. Final Answer:

    It imports variables from the parent scope into the closure. -> Option C
  4. Quick Check:

    use = import variables [OK]
Hint: Remember: use imports outside variables into closure [OK]
Common Mistakes:
  • Thinking use creates new variables inside closure
  • Confusing use with global keyword
  • Assuming use calls the closure
2. Which of the following is the correct syntax to pass a variable $x by reference into a closure using use?
easy
A. function() use ($x) { }
B. function() use (&x) { }
C. function() use ($&x) { }
D. function() use (&$x) { }

Solution

  1. Step 1: Understand passing by reference

    To allow a closure to modify an outside variable, it must be passed by reference using &.
  2. Step 2: Correct syntax with use

    The correct syntax is use (&$x) where & is before the variable name with the dollar sign.
  3. Final Answer:

    function() use (&$x) { } -> Option D
  4. Quick Check:

    Reference = & before $variable [OK]
Hint: Use & before $var inside use to pass by reference [OK]
Common Mistakes:
  • Placing & after $ or before variable name without $
  • Omitting & when intending to modify variable
  • Using invalid syntax like $&x
3. What will be the output of this PHP code?
$count = 0;
$func = function() use (&$count) { $count++; echo $count; };
$func();
$func();
echo $count;
medium
A. 111
B. 122
C. 120
D. Error

Solution

  1. Step 1: Analyze closure calls and reference

    The closure uses &$count by reference, so changes inside affect the outside variable.
  2. Step 2: Trace each call and output

    First call: increments count to 1 and echoes '1'. Second call: increments count to 2 and echoes '2'. Finally, outside echo prints 2.
  3. Final Answer:

    122 -> Option B
  4. Quick Check:

    Reference increments count = 122 [OK]
Hint: Reference in use means closure changes outside variable [OK]
Common Mistakes:
  • Assuming closure copies variable, so count stays 0
  • Expecting output '111' by mistake
  • Thinking code causes error
4. Identify the error in this PHP code snippet:
$x = 5;
$func = function() use ($x) { $x++; echo $x; };
$func();
echo $x;
medium
A. Output will be '65' because $x inside closure is a copy.
B. Runtime error because $x is undefined inside closure.
C. Syntax error because $x is not passed by reference.
D. Output will be '55' because closure does not run.

Solution

  1. Step 1: Understand variable binding without reference

    Using use ($x) passes $x by value, so closure gets a copy.
  2. Step 2: Trace output of closure and outside variable

    Closure increments its copy to 6 and echoes it. Outside $x remains 5, so echo prints 5.
  3. Final Answer:

    Output will be '65' because $x inside closure is a copy. -> Option A
  4. Quick Check:

    Value copy in use means outside unchanged [OK]
Hint: Without &, closure changes copy, not original variable [OK]
Common Mistakes:
  • Expecting outside $x to change without &
  • Thinking code causes syntax or runtime error
  • Confusing output order
5. Given this code, what will be the output?
$values = [1, 2, 3];
$sum = 0;
$funcs = [];
foreach ($values as $v) {
$funcs[] = function() use (&$sum, $v) { $sum += $v; };
}
foreach ($funcs as $f) { $f(); }
echo $sum;

Why does this output occur?
hard
A. 6, because each closure adds its own $v to $sum by value and $sum is by reference.
B. 3, because $v is shared and only last value is added multiple times.
C. 0, because closures do not run correctly.
D. Error, because $v cannot be used without reference.

Solution

  1. Step 1: Understand variable binding in loop closures

    Each closure captures $v by value (copy) and $sum by reference.
  2. Step 2: Trace closure execution

    Each closure adds its own $v (1, 2, 3) to the shared $sum. After all run, $sum = 6.
  3. Final Answer:

    6, because each closure adds its own $v to $sum by value and $sum is by reference. -> Option A
  4. Quick Check:

    Value copy for $v + reference $sum = 6 [OK]
Hint: Use value for loop var, reference for accumulator [OK]
Common Mistakes:
  • Assuming $v is shared reference causing wrong sum
  • Expecting error due to $v usage
  • Thinking closures do not run
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard