DEV Community

thiCha
thiCha

Posted on

Pipe operator is coming to PHP !

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")));
Enter fullscreen mode Exit fullscreen mode

With the pipe operator:

$result = "HELLO_WORLD"
    |> str_replace('_', ' ', ...)
    |> strtolower(...)
    |> ucfirst(...);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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)