In PHP, anonymous functions are also known as closures. They are functions without a specific name and can be assigned to variables, passed as arguments to other functions, or returned as values from functions. The keyword "use" is used in anonymous functions to import variables from the parent scope into the closure. This is useful when you want to access variables from the parent function that are not passed as arguments directly.
Remember that the use
keyword is crucial when you want to access variables from the parent scope inside an anonymous function. It ensures that the variables are available even if they are not defined as function arguments.
Basic usage of the use keyword: In this example, the anonymous function uses the use keyword to capture the $outerVariable from its parent scope, allowing it to access and return its value.
$outerVariable = 42; $anonymousFunction = function () use ($outerVariable) { return $outerVariable; }; echo $anonymousFunction(); // Output: 42
Modifying the captured variable: Here, the anonymous function captures both $baseValue and $modifier from the parent scope and uses them in its calculation.
$baseValue = 10; $modifier = 5; $calculate = function ($value) use ($baseValue, $modifier) { return ($value + $baseValue) * $modifier;}; echo $calculate(2); // Output: 60 ( (2 + 10) * 5 )
Using use with objects : In this example, the anonymous function captures an object instance ($object) from the parent scope and accesses its property.
class ExampleClass { public $property = "Hello"; } $object = new ExampleClass(); $anonymousFunction = function () use ($object) { return $object->property; }; echo $anonymousFunction(); // Output: Hello
Using use with an array : In this example, the anonymous function captures an array ($names) from the parent scope and checks if the provided name exists in that array to generate a greeting.
$names = ['John', 'Jane', 'Jake']; $greeting = function ($name) use ($names) { if (in_array($name, $names)) { return "Hello, $name!"; } else { return "Unknown person!"; } }; echo $greeting('Jane'); // Output: Hello, Jane! echo $greeting('Mike'); // Output: Unknown person!
Using "use" to pass multiple variables to a closure:
function processNumbers($a, $b) { return function ($operation) use ($a, $b) { switch ($operation) { case 'add': return $a + $b; case 'subtract': return $a - $b; case 'multiply': return $a * $b; case 'divide': return $a / $b; default: return "Invalid operation"; } }; } $calculator = processNumbers(10, 5); echo $calculator('add'); // Output: 15 echo $calculator('multiply'); // Output: 50