How to use First-class Callables in PHP 8.1

One of the very important concepts that every PHP developers should know is the concept of Callables. A callable is essentially an entity that can be invoked like a function. There are a number of ways you can create a PHP callable. For instance, to create a callable that references an object method, you can do something like this:

class MyClass {
    public function myMethod($arg) {
        echo "Method called with arg: $arg\n";
    }
}

$obj = new MyClass();
$callable = [$obj, 'myMethod'];
$callable("Hello"); // Outputs: Method called with arg: Hello

Similarly, when working with built-in functions, you could create a callable wrapper using Closure::fromCallable, as shown here:

$strlenCallable = Closure::fromCallable('strlen');
echo $strlenCallable("Hello"); // Outputs: 5

While these approaches work, a better and less verbose approach is desirable. Thankfully, PHP 8.1 introduces a brand new syntax for creating and using callables, fulfilling this desire.

Creating Callables with the New Syntax

So, how does the new syntax work? Let's consider an example where we have a class PaymentGateway with a method processPayment that we want to pass as a callable to another function. Here's how you can do it using the new syntax:

class PaymentGateway {
    public function processPayment(string $paymentMethod, float $amount): void {
        // Process the payment using the specified payment method
        echo "Processing payment of $amount using $paymentMethod\n";
    }
}

$paymentGateway = new PaymentGateway();
$processPaymentCallable = $paymentGateway->processPayment(...);
$processPaymentCallable("Credit Card", 100.0); // Outputs: Processing payment of 100 using Credit Card

As you can see, creating a callable from an object method is now much more straightforward. The (...) syntax clearly indicates that processPayment is a callable, making your code more readable and maintainable.

Using the New Syntax with Built-in Functions

The new syntax also applies to built-in functions, making it easy to create callable wrappers around functions like strlen or array_map. Here's an example:

$strlenCallable = strlen(...);
echo $strlenCallable("Hello"); // Outputs: 5

I prefer this new syntax over the old approaches because it's so much more concise and readable.

Conclusion

PHP 8.1's new callable syntax is a significant improvement over the previous approaches. By providing a more expressive and less verbose way to create callables, this new syntax can simplify your code and make it look cleaner. Whether you're working with object methods or built-in functions, the new syntax is a welcome addition to the PHP language. Go give it a try!

Wanna chat about what you just read, or anything at all? Click here to tweet at me on 𝕏