0
0
PHPprogramming~5 mins

Closures and variable binding with use in PHP

Choose your learning style9 modes available
Introduction
Closures let you create small functions inside other functions. Using 'use' helps these small functions remember variables from outside.
When you want a small function to remember a value from outside.
When you want to pass a function as a variable with some fixed data.
When you want to keep your code organized by grouping related logic.
When you want to delay using a variable until the function runs.
Syntax
PHP
<?php
$var = 'value';
$func = function() use ($var) {
    // code using $var
};
?>
The 'use' keyword brings outside variables into the closure.
Variables are copied by default, so changes inside the closure don't affect outside.
Examples
This closure remembers the $message variable and prints 'Hello'.
PHP
<?php
$message = 'Hello';
$sayHello = function() use ($message) {
    echo $message;
};
$sayHello();
?>
Using & before $count lets the closure change the original $count variable.
PHP
<?php
$count = 0;
$increment = function() use (&$count) {
    $count++;
    echo $count;
};
$increment();
$increment();
?>
Sample Program
This program shows a closure printing a greeting and another closure adding a number from outside.
PHP
<?php
$greeting = 'Hi';
$greeter = function() use ($greeting) {
    echo "$greeting, friend!\n";
};
$greeter();

$number = 5;
$addNumber = function($x) use ($number) {
    return $x + $number;
};
$result = $addNumber(10);
echo "10 + $number = $result\n";
?>
OutputSuccess
Important Notes
Without 'use', closures cannot access variables outside their own scope.
Using '&' before a variable in 'use' means the closure can change the original variable.
Be careful with references to avoid unexpected changes outside the closure.
Summary
Closures are functions inside functions that can remember outside variables.
The 'use' keyword brings outside variables into closures.
Use '&' in 'use' to allow the closure to change outside variables.