New Features in PHP 8.4: A Comprehensive Guide with Code Examples
`PHP 8.4`, released in November 2024, introduces a host of powerful features and improvements that streamline development, enhance code expressiveness, and address long-standing developer requests. Here’s a detailed look at the most impactful additions, complete with code examples.
Property Hooks: Custom `Getters` and `Setters` Without Boilerplate
Property hooks allow you to define custom logic for getting and setting class properties, eliminating the need for verbose `getter` and `setter` methods. Inspired by languages like Kotlin and C#, this feature brings a more declarative way to control property access and mutation.
class User { public string $firstName { set(string $name) { $this->firstName = ucfirst($name); } } public string $lastName { set(string $name) => ucfirst($name); } public string $fullName { get => $this->firstName . ' ' . $this->lastName; set(string $name) { [$this->firstName, $this->lastName] = explode(' ', $name, 2); } } } $user = new User(); $user->firstName = 'ash'; $user->lastName = 'allen'; echo $user->fullName; // Ash Allen
You can also use the new `__PROPERTY__` magic constant inside hooks to reference the property name.
Asymmetric Property Visibility: Fine-Grained Control Over Read/Write
With asymmetric visibility, you can now assign different visibility levels for reading and writing a property. For example, a property can be publicly readable but only privately writable, which is especially useful for value objects and DTOs.
class Book { public private(set) string $title; public protected(set) string $author; public function __construct(string $title, string $author) { $this->title = $title; $this->author = $author; } } $book = new Book('PHP 8.4', 'Jane Doe'); echo $book->title; // Allowed $book->title = 'New Title'; // Error: cannot set outside class
This syntax also works with promoted constructor properties.
New Array Functions: `array_find`, `array_find_key`, `array_any`, `array_all`
`PHP 8.4` introduces several new array functions that simplify common search and filter operations:
- `array_find($array, $callback)`: Returns the first matching element.
- `array_find_key($array, $callback)`: Returns the key of the first matching element.
- `array_any($array, $callback)`: Returns true if any element matches.
- `array_all($array, $callback)`: Returns true if all elements match.
$numbers = [1, 2, 3, 4, 5, 6]; $firstEven = array_find($numbers, fn($n) => $n % 2 === 0); // 2 $firstEvenKey = array_find_key($numbers, fn($n) => $n % 2 === 0); // 1 $hasEven = array_any($numbers, fn($n) => $n % 2 === 0); // true $allEven = array_all($numbers, fn($n) => $n % 2 === 0); // false
Class Instantiation Without Extra Parentheses
Previously, chaining methods or accessing properties on a newly instantiated object required wrapping the new expression in parentheses. `PHP 8.4` removes this requirement, making code cleaner and more intuitive:
// Before PHP 8.4 $name = (new ReflectionClass($object))->getShortName(); // Now in PHP 8.4 $name = new ReflectionClass($object)->getShortName();
This applies to accessing methods, properties, static methods, and constants directly after `new`.
`HTML5`-Compliant `DOM` API
`PHP 8.4` introduces new `DOM` classes that are fully standards-compliant with `HTML5`, fixing several long-standing bugs and making HTML parsing more reliable. The new API is available alongside the old one for backward compatibility.
$dom = Dom\HTMLDocument::createFromString('<main><article class="featured">Hello</article></main>'); $node = $dom->querySelector('main > article.featured'); echo $node->textContent; // Hello
New Multibyte String Functions
Working with multibyte strings is easier with the addition of these functions:
- `mb_trim()`, `mb_ltrim()`, `mb_rtrim()`: Multibyte-safe trimming.
- `mb_ucfirst()`, `mb_lcfirst()`: Multibyte-safe case conversion.
$str = " Hello "; echo mb_trim($str); // "Hello" echo mb_ucfirst("hello"); // "Hello"
Other Notable Improvements
- `#[Deprecated]` AttributeMark functions, classes, or properties as deprecated using the new attribute syntax.
- Enhanced Password Hashing: The default `bcrypt` cost increased from `10` to `12` for better security.
- Expanded `HTTP` Verb Support: `$_POST` and `$_FILES` now support additional `HTTP` verbs.
- Driver-specific `PDO` Subclasses: Access driver-specific features directly from `PDO` subclasses.
- Performance and Compatibility: Updates to `JIT`, `OpenSSL`, `libcurl`, and Unicode support.
Conclusion
`PHP 8.4` is a feature-rich release that modernizes the language and reduces boilerplate. Features like property hooks, asymmetric visibility, new array utilities, and cleaner class instantiation syntax will have a significant positive impact on day-to-day development.
0%