← All writing
 ·  1 min read

The PHP 8.5 Pipe Operator (|>): Useful, but Watch for These Gotchas

I have been eagerly waiting for the pipe operator ever since I first encountered it in the RFC proposals years back. Finally, with the release of PHP 8.5 yesterday, I had the chance to put the implementation into practice. Here are a few things worth noting.

The PHP 8.5 Pipe Operator (|>): Useful, but Watch for These Gotchas

I have been eagerly waiting for the pipe operator ever since I first encountered it in the RFC proposals years back. The pipe operator lets you chain function calls without creating a bunch of temporary variables. It flips nested code inside-out into something you can read top to bottom — like a normal human. Finally, with the release of PHP 8.5 yesterday, I had the chance to put the implementation into practice. Here are a few things worth noting:

  1. If you are using arrow functions fn($x) => $x, you need to wrap them in parentheses (fn($x) => $x). This will make them callable for the pipe operator.
  2. Anonymous functions are callable without parentheses.
  3. It only works with a single argument; if you need more arguments, you must wrap the function in a callable. This will act as a type of single argument proxy: (fn($x) => str_replace('!', ',', $x)).

Here is a breakdown of the ways you can use the pipe |> operator in code:

php
<?php
$result = "   Hello World!   "
        |> 'strtoupper'
        |> trim(...)
        |> (fn($x) => str_replace('!', ',', $x))
        |> function(string $x): string {return strtolower($x);}
        |> new MyClass()
        |> new MyClass()->myInstanceMethod(...)
        |> [MyClass::class, 'myStaticMethod']
        |> my_function(...);

echo $result;

function my_function(string $x): string {
    return $x . ' Functions are fastest!';
}

class MyClass {
    public function __invoke(string $x): string {
        return $x . ' instantiated';
    }

    public function myInstanceMethod(string $x): string {
        return $x . ' objects';
    }

    public static function myStaticMethod(string $x): string {
        return $x . ' are slower than statics methods!';
    }
}

You can read more about the story of the pipe operator in the official blog post "PHP 8.5 Adds Pipe Operator: What it means."