28 November 2026

PHP 8.5 Pipe Operator and Property Hooks for Beginners: Cleaner Code

  Asp.Net CS By Example       28 November 2026

Modern PHP has evolved dramatically beyond basic server scripts. With PHP 8.4 property hooks, you can validate and format object properties directly inside a class without writing repetitive getName() and setName() methods. With PHP 8.5's pipe operator (|>), you can transform strings and arrays cleanly from left to right instead of nesting function calls inside each other.

Two modern PHP upgrades

Property Hooks { get; set; } (Clean OOP validation) • $raw |> trim(...) |> strtolower(...) (Readable data flow)

1. Validate and Format Fields with Property Hooks (PHP 8.4+)

In the StudentProfile class below, $name uses a backed set/get hook to trim and capitalize names, while $summary is a read-only virtual property computed on the fly:

<?php

class StudentProfile
{
    public string $name {
        get => ucfirst($this->name);
        set(string $value) {
            $clean = trim($value);
            if ($clean === '') {
                throw new InvalidArgumentException('Student name cannot be empty.');
            }
            $this->name = $clean;
        }
    }

    public string $summary {
        get => $this->name . ' (' . $this->track . ')';
    }

    public function __construct(string $name, public string $track)
    {
        $this->name = $name;
    }
}

$student = new StudentProfile('  maya  ', 'ASP.NET Core');
echo $student->name . PHP_EOL;     // Output: Maya
echo $student->summary . PHP_EOL;  // Output: Maya (ASP.NET Core)

2. Chain Steps Left-to-Right with the Pipe Operator (PHP 8.5+)

Instead of writing deeply nested calls like str_replace(' ', '-', strtolower(trim($raw))), pass values through the |> pipe operator:

<?php

$courseTitle = '  Modern PHP Basics  ';

$slug = $courseTitle
    |> trim(...)
    |> strtolower(...)
    |> (fn(string $text) => str_replace(' ', '-', $text));

echo $slug; // Output: modern-php-basics

Practice

  1. Add an integer $score property with a set hook that throws an InvalidArgumentException if the value is below 0 or above 100.
  2. Use the pipe operator (|>) to trim a comma-separated tag string, convert it to lowercase, and split it with explode(',', ...).
  3. Add a virtual $passed boolean property using get => $this->score >= 60;.

Continue learning: PHP Lessons and Practice.

References: PHP Official Documentation.

logoblog

Thanks for reading PHP 8.5 Pipe Operator and Property Hooks for Beginners: Cleaner Code

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.