First Class Callable Syntax

In PHP 8.1 and later, first-class callable syntax allows you to create references to callable functions or methods in a cleaner and more intuitive way using the (...) syntax.

Here’s an example:

1. Function Callables

You can create a callable for a function like this:

function sayHello($name) {
return "Hello, $name!";
}

$callable = sayHello(...); // First-class callable syntax

echo $callable("World"); // Outputs: Hello, World!

2. Method Callables

For methods inside a class, you can do the same with static or instance methods.

Static method:

class Greeter {
public static function greet($name) {
return "Hello, $name!";
}
}

$callable = Greeter::greet(...); // First-class callable for a static method

echo $callable("Alice"); // Outputs: Hello, Alice!

Instance method:

class Greeter {
public function greet($name) {
return "Hi, $name!";
}
}

$greeter = new Greeter();
$callable = $greeter->greet(...); // First-class callable for an instance method

echo $callable("Bob"); // Outputs: Hi, Bob!

This syntax is a cleaner alternative to the older call_user_func and array-based callable styles, offering better performance and readability.

Leave a Reply

Your email address will not be published. Required fields are marked *