Advanced topics (anonymous functions, closures, arrow functions)

🔥 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:

FeatureClosureArrow Function
SyntaxLongShort
use keywordRequiredNot needed
ScopeManualAutomatic

✅ 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:

  1. Use array_map with arrow function to square numbers
  2. Create closure that counts function calls
  3. Build a custom filter function
  4. Sort array of objects using closure
  5. Create a function that returns another function (closure)