Closures aur Arrow Functions
Ek anonymous function function ($params) { ... } ki tarah likha jaata hai, function ke baad koi naam nahi hota — ye ek value hai, kisi bhi doosri value ki tarah ek variable ko assignable. By default ye us scope ke variables nahi dekh sakta jisme ye likha gaya tha; function header par use ($var) surrounding scope se $var ko value ke through explicitly capture karta hai, closure ko use read karne deta hai.
fn($params) => $expression, jo PHP 7.4 mein add hua, ek shorter arrow-function form hai us common case ke liye jahan closure sirf ek expression ho — aur function (...) use (...) form ke unlike, ye outer variables ko automatically capture karta hai, koi use list ki zaroorat nahi. Ye Python ke lambda ya JavaScript ke arrow functions ka PHP jawab hai, aur idiomatic modern PHP mein array_map(), array_filter(), aur friends ke andar yahi pass hota dikhega.
<?php
$multiplier = 3;
$multiply = function ($x) use ($multiplier) {
return $x * $multiplier;
};
echo $multiply(5), "\n";
$square = fn($x) => $x * $x;
echo $square(6), "\n";
$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
print_r($doubled);
15
36
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)$multiply(5) 5 * 3 hai, $multiplier ko use se explicitly capture karke; $square(6) 6 * 6 hai, shorter fn() form use karke bilkul bina use list ke. array_map(fn($n) => $n * 2, $nums) ne wo arrow function $nums ke har element par ek call mein apply kiya — is tarah ki transformation ke liye idiomatic PHP almost hamesha hand-written loop ke upar array_map reach karta hai. Next: classes and objects — class keyword, $this, constructors, aur properties.
Practice exercise
$nums = [1, 2, 3, 4] diya gaya hai, array_map() ko ek arrow function ke saath use karke har element ko square karo, phir implode() use karke results ko ", " se joined echo karo.