How to Use Closure in PHP: Syntax and Examples
In PHP, a
closure is an anonymous function that can capture variables from its surrounding scope using the use keyword. You define a closure with function() syntax and can assign it to a variable or pass it as a callback.Syntax
A closure in PHP is an anonymous function that can capture variables from the outside scope using the use keyword.
- function(): Defines the anonymous function.
- use ($var): Imports variables from the parent scope.
- { ... }: Contains the function body.
php
<?php $closure = function() use ($var) { // function body };
Example
This example shows a closure capturing a variable from outside its scope and using it inside the function.
php
<?php $message = 'Hello'; $greet = function($name) use ($message) { return "$message, $name!"; }; echo $greet('Alice');
Output
Hello, Alice!
Common Pitfalls
One common mistake is forgetting to import variables with use, which causes an error or undefined variable inside the closure. Also, variables imported with use are copied by value, so changes inside the closure do not affect the original variable unless passed by reference.
php
<?php $count = 0; // Wrong: variable not imported $increment = function() { $count++; // Error: undefined variable }; // Right: import by reference to modify original $increment = function() use (&$count) { $count++; }; $increment(); echo $count; // Outputs 1
Output
1
Quick Reference
- Use
function() use ($var)to capture variables. - Variables are copied by value unless passed by reference with
&. - Closures can be assigned to variables or passed as callbacks.
- Closures help write flexible, reusable code blocks.
Key Takeaways
Closures are anonymous functions that can capture variables from outside using the use keyword.
Variables imported with use are copied by value unless passed by reference with &.
Closures can be stored in variables and passed as callbacks for flexible code.
Always import needed variables with use to avoid undefined variable errors.
Use closures to write concise and reusable blocks of code.