First-class callable syntax lets you treat functions like variables. You can store, pass, and use them easily.
First-class callable syntax in PHP
$callable = function_name(...);
Use the function name followed by (...) to get a callable.
This syntax was introduced in PHP 8.1 for cleaner and simpler code.
strlen function as a callable and use it.$strlenCallable = strlen(...); echo $strlenCallable('hello');
greet as a callable and call it.function greet($name) { return "Hello, $name!"; } $greetCallable = greet(...); echo $greetCallable('Alice');
array_map to double numbers.$numbers = [1, 2, 3]; $double = fn($n) => $n * 2; $doubledNumbers = array_map($double, $numbers); print_r($doubledNumbers);
trim to clean array strings.$trimCallable = trim(...); $words = [' apple ', ' banana ', ' cherry ']; $trimmed = array_map($trimCallable, $words); print_r($trimmed);
This program defines a function square that returns the square of a number. It then stores this function as a callable using first-class callable syntax. Using array_map, it applies the callable to each number in the array and prints the results.
<?php function square($x) { return $x * $x; } $squareCallable = square(...); $values = [2, 3, 4]; $squaredValues = array_map($squareCallable, $values); foreach ($squaredValues as $value) { echo $value . "\n"; }
First-class callable syntax only works with named functions or methods, not with anonymous functions directly.
You can also use this syntax with class methods like ClassName::methodName(...).
This syntax makes code cleaner and easier to read compared to older ways of creating callables.
First-class callable syntax lets you treat functions like variables easily.
Use function_name(...) to get a callable for that function.
This helps when passing functions as arguments or storing them for later use.