Pipe Operator in PHP
The pipe operator (|>
) is a powerful addition coming in PHP 8.5 that enables clean and readable chaining of functions. Inspired by functional programming, it simplifies the process of applying multiple transformations to a value by passing the result of one expression directly into the next. This helps avoid deep nesting and makes code easier to read and maintain.
How it works?
The pipe operator takes the value on the left side and passes it as the only argument to the callable on the right side. It supports:
The right-hand callable must accept exactly one parameter.
Example: Traditional Approach
$donut = addCrumbs(
addChocolate(
addMarshmallow(
addHearts(
addSprinkles(
addIcing(
bakeDonut()
)
)
)
)
)
);
Example: With Pipe Operator
$donut = bakeDonut()
|> addIcing(...)
|> addSprinkles(...)
|> addHearts(...)
|> addMarshmallow(...)
|> addChocolate(...)
|> addCrumbs(...);
This linear flow improves readability and reflects the natural order of operations.
Syntax
$output = $input
|>trim(...)
|> fn(string $s) => str_replace(' ', '-', $s)
|> fn(string $s) => str_replace(['.', '/', '…'], '', $s)
|> strtolower(...);
Each function receives the output of the previous one, eliminating the need for temporary variables.
Further Reading
The pipe operator brings clarity to PHP code, making it easier to work with complex transformations. It is a welcome feature for developers aiming to write more expressive and maintainable code.
I began my WordPress journey in 2013 by editing themes, sparking my passion for web development. By 2016, I had transitioned into a professional WordPress developer role. Over the years, I’ve worked with various companies and on numerous projects, eventually leading development teams and guiding projects from conception to completion. As a WordPress enthusiast, I am dedicated to building innovative solutions and contributing to the WordPress community.