A new operator is coming to PHP: the pipe ! (|>)
Just like in linux, you will now be able to chain multiple commands together.
What it is
This operator will help us make the code more readable and expressive.
Before:
$result = ucfirst(strtolower(str_replace('_', ' ', "HELLO_WORLD")));
With the pipe operator:
$result = "HELLO_WORLD"
|> str_replace('_', ' ', ...)
|> strtolower(...)
|> ucfirst(...);
The other way to make the first example readable is to use a temporary variable:
$result = "HELLO_WORLD";
$result = str_replace('_', ' ', $result);
$result = strtolower($result);
$result = ucfirst($result);
The pipe operator gives you clean style to chain calls.
How to use it
In PHP, we use callables so we have multiple ways to use it:
- userland functions
- built-in functions
- static class methods
- lambda functions
- arrow-functions
- invokable classes
- first-class callables.
Here’s a demo:
$result = "42"
|> intval(...)
|> fn($x) => $x * 2
|> function(int $x): string { return "Value: $x"; }
|> new Transformer()
|> [MathHelper::class, 'addExclamation']
|> format_output(...);
echo $result; // Value: 84!
The drawback
“Perfect,” you might think — and almost!
But there’s a small limitation.
The pipe operator only works when the result of the previous can be passed as the first argument of the next callable.
So while the pipe operator makes code cleaner, it does have some functional-style constraints you’ll need to keep in mind.
Conclusion
The pipe operator brings a fresh, functional touch to PHP — making our code flow as smoothly as our ideas.
Top comments (0)