Closures & Arrow Functions
Closure (Anonymous Function)
Fungsi tanpa nama. Gunakan use untuk mengakses variabel luar.
Arrow Function (PHP 7.4+)
Syntax singkat: fn($x) => $x * 2. Otomatis capture variabel luar (by value).
Fungsi tanpa nama. Gunakan use untuk mengakses variabel luar.
Syntax singkat: fn($x) => $x * 2. Otomatis capture variabel luar (by value).
<?php
// Closure
$greet = function(string $name): string {
return "Hello, $name!";
};
echo $greet("World") . "
";
// Closure with use
$prefix = "Mr.";
$formal = function(string $name) use ($prefix): string {
return "$prefix $name";
};
echo $formal("Ali") . "
";
// Arrow function (PHP 7.4+)
$double = fn($n) => $n * 2;
echo "double(5): " . $double(5) . "
";
// Arrow auto-captures outer vars
$multiplier = 3;
$multiply = fn($n) => $n * $multiplier;
echo "multiply(7): " . $multiply(7) . "
";
// With array functions
$nums = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $nums);
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
echo "Doubled: " . implode(",", $doubled) . "
";
echo "Evens: " . implode(",", $evens);
?>