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:
- 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. - Anonymous functions are callable without parentheses.
- 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
$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.”



Leave a Reply