Reference: PHP 8.5 Pipe Operator
⚠️ The pipe operator (
|>
) is only available in PHP 8.5 and above. Attempting to use it in earlier versions will cause a syntax error.
Introduction
PHP 8.5 introduces the long-awaited pipe operator (|>
), making it easier to chain function calls and write cleaner, more readable code.
How Does It Work?
- The
...
(spread operator) is the placeholder for the value passed from the previous step. - Each function in the chain receives the output of the previous function as its input.
- You can combine as many actions as you like, making your transformations clear and concise.
Let's see how you might manipulate an array of fruits in PHP, first using traditional code, then with the new pipe operator.
Without the Pipe Operator
Here's how you might perform a series of transformations on an array in classic PHP:
$fruits = ["apple", "banana", "cherry"];
$fruits = array_map(fn($f) => strtoupper($f), $fruits);
$fruits = array_filter($fruits, fn($f) => str_starts_with($f, 'A'));
$fruits = array_values($fruits);
print_r($fruits); // ["APPLE"]
With the Pipe Operator
With PHP 8.5's pipe operator, you can chain these operations more elegantly:
$fruits = ["apple", "banana", "cherry"]
|> array_map(fn($f) => strtoupper($f), ...)
|> array_filter(..., fn($f) => str_starts_with($f, 'A'))
|> array_values(...);
print_r($fruits); // ["APPLE"]
Each function receives the result of the previous one, making your code more readable and expressive.
Limitations & Gotchas
- Only One Required Parameter: All callables in the pipe chain must accept the piped value as their first (and only required) parameter. You cannot change the position.
- Callable Flexibility: You can use user functions, built-in functions, static methods, anonymous functions, arrow functions, objects with
__invoke
, and first-class callables. - Type Coercion: The pipe operator follows PHP’s normal type coercion rules. If
strict_types
is enabled, type mismatches will throw errors. - Void Return Types: Functions with void return types can be piped, but the value becomes
null
for the rest of the chain. Typically, use void functions last. - By-Reference Limitation: Functions requiring by-reference parameters (e.g.,
array_pop
) cannot be used in a pipe chain, except for a few special cases likearray_multisort
andextract
.
Final Thoughts
The PHP 8.5 pipe operator is a game-changer for writing expressive, readable code. Whether you’re transforming arrays, objects, or other data, it’s a powerful new tool in your PHP arsenal.