The PHP 8.5 pipe operator forwards a value to a single-argument callable in readable stages.
What It Does and When to Use It
Use a pipeline to process a value through one-argument callables. A minimum platform requirement controls what syntax can be parsed; target-version tests find runtime and extension incompatibilities.
Requirements, Inputs and Expected Behavior
The code using the pipe operator, NoDiscard, or void cast requires PHP 8.5 or later; code with older syntax can still run on earlier supported PHP releases. Each stage must accept one value; use a closure to adapt functions needing more parameters.
Example 1: Basic Operation
Use a pipeline to process a value through one-argument callables.
<?php
$slug = ' A New Guide '
|> trim(...)
|> strtolower(...)
|> (fn (string $s) => str_replace(' ', '-', $s));
echo $slug;
Example 2: Behavior and Validation
Adapt a callable with a closure when extra arguments or transformations are needed.
<?php
$total = [10, 20, 30]
|> array_sum(...)
|> (fn (int $sum) => $sum * 1.17);
echo $total;
Practical Example: Application Use
Compose a named function and a closure, requiring PHP 8.5 or later.
<?php
function normalize(string $input): string { return strtolower(trim($input)); }
$result = ' [email protected] '
|> normalize(...)
|> (fn (string $s) => explode('@', $s)[0]);
echo $result;
Important Behavior and Edge Cases
The second example highlights: Adapt a callable with a closure when extra arguments or transformations are needed. The practical example adds: Compose a named function and a closure, requiring PHP 8.5 or later.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Minimum PHP version and target PHP version | A minimum platform requirement controls what syntax can be parsed; target-version tests find runtime and extension incompatibilities. |
| Choosing safely | Do not introduce syntax from a newer minor version before every production host supports it. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming newer syntax parses on older PHP | Lint with the oldest supported runtime; gate or delay newer syntax. |
| Upgrading CLI PHP but not the web worker | Check the FPM binary, all extensions and the Composer platform in staging. |
| Skipping operational constraints | Each stage must accept one value; use a closure to adapt functions needing more parameters. |
Key Takeaways
- The PHP 8.5 pipe operator forwards a value to a single-argument callable in readable stages.
- Compose a named function and a closure, requiring PHP 8.5 or later.
- Do not introduce syntax from a newer minor version before every production host supports it.