0
0
PHPprogramming~5 mins

First-class callable syntax in PHP

Choose your learning style9 modes available
Introduction

First-class callable syntax lets you treat functions like variables. You can store, pass, and use them easily.

When you want to pass a function as an argument to another function.
When you want to store a function in a variable for later use.
When you want to return a function from another function.
When you want to simplify callback syntax in array functions.
When you want to avoid writing anonymous functions for simple callbacks.
Syntax
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.

Examples
Store the built-in strlen function as a callable and use it.
PHP
$strlenCallable = strlen(...);
echo $strlenCallable('hello');
Store a user-defined function greet as a callable and call it.
PHP
function greet($name) {
    return "Hello, $name!";
}
$greetCallable = greet(...);
echo $greetCallable('Alice');
Use a callable (anonymous function) with array_map to double numbers.
PHP
$numbers = [1, 2, 3];
$double = fn($n) => $n * 2;
$doubledNumbers = array_map($double, $numbers);
print_r($doubledNumbers);
Use first-class callable syntax with trim to clean array strings.
PHP
$trimCallable = trim(...);
$words = ['  apple ', ' banana  ', ' cherry '];
$trimmed = array_map($trimCallable, $words);
print_r($trimmed);
Sample Program

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
<?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";
}
OutputSuccess
Important Notes

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.

Summary

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.