Back to results for “Scope”
PHP › Closures & Anonymous Functions

What is the use keyword in a PHP closure, and why is it needed to access outside variables from within an anonymous function?

Beginner

Answer

By default, an anonymous function in PHP does not have access to variables from the surrounding scope where it was defined, so the use keyword explicitly lets you import specific outside variables into the closure, making them available inside the anonymous function's own body, which is necessary because closures otherwise operate in an isolated scope for clarity and to avoid unintended side effects.
$taxRate = 0.08;
$calculateTax = function ($price) use ($taxRate) {
    return $price * $taxRate;
};
echo $calculateTax(100);
Real-world example A pricing calculation function uses the use keyword to bring the current tax rate into a closure responsible for calculating tax on individual product prices, keeping that shared value accessible without making it a global variable.

Common follow-ups: What is the difference between passing a variable into use by value versus by reference?;What happens if you modify a use variable inside the closure without passing it by reference?