PHP
Capturing variables with use
Learn to capture outer scope variables into a closure with use.
Capture outer variables with use
A closure cannot directly reach variables from the scope where it was defined. With the use keyword you capture the outer variable inside.
Example: $msg = 'Hello'; $greet = function () use ($msg) { echo $msg; };. Here $msg is copied at the moment the closure is defined.
The default behavior is by value. So even if $msg is changed inside the closure, the outer $msg is not affected.
Capture by reference: &$var
Sometimes you want a change inside the closure to affect the outer variable too. With the & sign you capture by reference.
Example: function () use (&$counter) { $counter++; }. Here the closure takes $counter itself; the increment raises the outer variable too.
Reference is useful for counter or accumulator patterns; but use it carefully, since it mutates state.
Exercise Capture the tax rate with use
$tax = 0.18; is given. Define a closure named $addTax: capture the outer $tax with function ($price) use ($tax) and return $price * (1 + $tax). Then print the result with echo $addTax(100) . "\n";.
Show example solution
Write $addTax = function ($price) use ($tax) { return $price * (1 + $tax); };. Then call echo $addTax(100) . "\n";.
Example solution:
<?php
// Capture the tax rate with use in a closure
$tax = 0.18;
$addTax = function ($price) use ($tax) {
return $price * (1 + $tax);
};
echo $addTax(100) . "\n";
Test yourself
-
How is a captured variable copied by default with use?
- By value
- By reference
- As a constant
- In read-only mode
Show answer
By value — Correct. use copies the variable by value; inner changes do not affect the outer one.
-
Complete the use clause
<?php
$msg = 'Hello';
$greet = function () ____ ($msg) {
return ['text' => $msg];
};
print_r($greet());
Show answer
<?php
$msg = 'Hello';
$greet = function () use ($msg) {
return ['text' => $msg];
};
print_r($greet());
-
Match the capture forms with use
- use ($x)
- Captures by value
- use (&$x)
- Captures by reference
- use (&$counter)
- Updates outer counter
Next lesson: Arrow functions (fn)