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.
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
- Add an integer
$scoreproperty with asethook that throws anInvalidArgumentExceptionif the value is below0or above100. - Use the pipe operator (
|>) to trim a comma-separated tag string, convert it to lowercase, and split it withexplode(',', ...). - Add a virtual
$passedboolean property usingget => $this->score >= 60;.
Continue learning: PHP Lessons and Practice.
References: PHP Official Documentation.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.