Sobes.tech
Junior — Middle

How to access a variable captured inside a closure in PHP?

sobes.tech AI

Answer from AI

In PHP, the use keyword is used to access variables from an external scope inside a closure. It allows capturing variables by value or by reference.

Example:

$message = 'Hello';

$closure = function() use ($message) {
    echo $message;
};

$closure(); // Outputs: Hello

If you need to modify the variable's value inside the closure and have the changes persist outside of it, you should capture the variable by reference:

$count = 0;

$increment = function() use (&$count) {
    $count++;
};

$increment();
echo $count; // Outputs: 1
How to access a variable captured inside a closure in… - sobes.tech