🔥 1. Anonymous Functions (Closures Basics)
👉 Anonymous functions = functions without a name
✅ Syntax:
$func = function() {
echo "Hello World";
};$func(); // call it
👉 You store the function in a variable and then call it.
✅ With Parameters:
$sum = function($a, $b) {
return $a + $b;
};echo $sum(5, 3);
📌 Where used in real life:
- Callbacks
- Array functions (
array_map,array_filter) - Event handling
✅ Example with array:
$numbers = [1, 2, 3];$result = array_map(function($n) {
return $n * 2;
}, $numbers);print_r($result);
🔥 2. Closures (Very Important)
👉 A closure is an anonymous function that can access variables from outside using use.
❗ Problem (Without Closure)
$msg = "Hello";$func = function() {
echo $msg; // ❌ Error (undefined)
};
✅ Solution (Using use)
$msg = "Hello";$func = function() use ($msg) {
echo $msg;
};$func();
🔁 Pass by Reference in Closure
$count = 0;$increment = function() use (&$count) {
$count++;
};$increment();
$increment();echo $count; // 2
📌 Real Use Case:
- Capturing environment variables
- Middleware (Laravel, Express-like logic)
- Custom callbacks
🔥 3. Arrow Functions (PHP 7.4+)
👉 Short syntax for writing functions
✅ Syntax:
$sum = fn($a, $b) => $a + $b;
✅ Example:
echo $sum(10, 5);
📌 Key Difference from Closure:
| Feature | Closure | Arrow Function |
|---|---|---|
| Syntax | Long | Short |
use keyword | Required | Not needed |
| Scope | Manual | Automatic |
✅ Example with array:
$nums = [1, 2, 3];$result = array_map(fn($n) => $n * 3, $nums);print_r($result);
⚠️ Important Differences
🔸 Closure vs Arrow Function
👉 Closure:
$x = 5;$func = function() use ($x) {
return $x * 2;
};
👉 Arrow:
$x = 5;$func = fn() => $x * 2;
🔸 Limitation of Arrow Function
👉 Only single expression allowed
❌ Not allowed:
fn($x) => {
$y = $x * 2;
return $y;
};
💡 Real-World Examples
✅ 1. Filter Even Numbers
$nums = [1,2,3,4,5,6];$even = array_filter($nums, fn($n) => $n % 2 == 0);print_r($even);
✅ 2. Custom Sorting
$users = [
["name" => "A", "age" => 25],
["name" => "B", "age" => 20]
];usort($users, fn($a, $b) => $a['age'] <=> $b['age']);print_r($users);
✅ 3. Simple Middleware (Concept)
function middleware($next) {
return function($request) use ($next) {
echo "Before\n";
$next($request);
echo "After\n";
};
}
🧠 Interview-Level Insights
👉 Interviewers may ask:
❓ Why use closures?
- Encapsulation
- Cleaner callbacks
- Avoid global variables
❓ Arrow vs Closure?
👉 Arrow:
- Short
- Automatic variable capture
👉 Closure:
- More powerful
- Supports multiple statements
❓ When NOT to use arrow functions?
- When logic is complex
- When multiple statements needed
- When modifying external variables
🎯 Practice Questions
Try these:
- Use
array_mapwith arrow function to square numbers - Create closure that counts function calls
- Build a custom filter function
- Sort array of objects using closure
- Create a function that returns another function (closure)






