By Akshay Maradiyaauthor-img
November 19, 2024|9 Minute read|
Play
/ / What to expect in PHP 8.4: Major features and Changes

Introduction

PHP 8.4 is scheduled to be released on November 21st, 2024. It is full of advanced functionalities and features to improve performance and developer experience. This is part of PHP’s annual release cycle.

PHP release dates so far have been:

 

PHP 8.4 and previous releases

The November update for PHP will redefine a lot of possibilities in web development. PHP has almost over 75 million websites depending on it. The PHP 8.4 release will recognize the evolving needs of developers. This blog gives you an overview on the innovative functionalities and features that will help in better systems development.


PHP 8.4 Features

As such, PHP 8.4 offers many updates and new features to simplify development and improve your overall experience. In this blog, we are going to look at some of the most significant features of PHP 8.4.

  • Property Hooks

  • New Array Functions

  • Instantiating Classes Without Parentheses for Immediate Method Calls

  • Asymmetric Property Visibility

  • HTML5 Parsing and Serialization

 

Property Hooks

With PHP 8.4, Property Hooks introduce a streamlined way to enforce validation and manage properties directly, reducing the need for boilerplate getters and setters. Property Hooks let developers define "get" and "set" hooks, allowing custom logic to be executed when a property is accessed or modified. This powerful feature simplifies property management and improves readability in PHP code.


<?php 
class User { 

    private bool $isModified = false; 

    public function __construct(private string $firstName, private string $lastName) {} 

    public string $fullName { 
        // "get" hook to concatenate first and last names 
        get => $this->firstName . " " . $this->lastName; 

        // "set" hook to split a full name string into first and last names 
        set { 
            [$this->firstName, $this->lastName] = explode(' ', $value, 2); 
            $this->isModified = true; 
        } 
    } 
} 

// Usage 
$user = new User('John', 'Doe'); 
echo $user->fullName; // Outputs: "John Doe" 

$user->fullName = 'Jane Smith'; // Updates firstName and lastName 
echo $user->fullName; // Outputs: "Jane Smith"
    


In this example, the $fullName property has hooks to manage concatenation and splitting of names automatically, eliminating the need for separate getter and setter methods. 

 

Validating Properties with Property Hooks

Property Hooks also allow validation directly in the "set" hook.


<?php
class Person {

    public string $fullName {
        get => $this->firstName . ' ' . $this->lastName;
    }

    public string $firstName {
        set => ucfirst(strtolower($value));
    }

    public string $lastName {
        set {
            if (strlen($value) < 2) {
                throw new \InvalidArgumentException('Last name must be at least 2 characters');
            }
            $this->lastName = $value;
        }
    }
}

// Usage
$person = new Person();
$person->firstName = 'peter';     // Becomes "Peter"
echo $person->firstName;         // Outputs: "Peter"
$person->lastName = 'Peterson';  // Valid assignment
echo $person->fullName;          // Outputs: "Peter Peterson"

// $person->lastName = 'P';       // Throws InvalidArgumentException
    


Why Property Hooks Matter?

Property Hooks make property validation and formatting simpler, providing a powerful new way to manage properties directly. They also allow properties on interfaces, adding flexibility and control.


New Array Functions

PHP 8.4 introduces four new array functions—array_all, array_any, array_find, and array_find_key—which make array operations simpler and more readable by handling checks and searches more intuitively. Here is a closer look at each of these functions with explanations and examples.


1. array_all

The array_all function checks if all elements in an array satisfy a given callback condition. If every element meets the condition, array_all returns true; otherwise, it returns false. This can be particularly useful for ensuring data integrity across all elements.
 
Syntax:


array_all(array $array, callable $callback): mixed
    

Example:


<?php
$array = ['apple', 'banana', 'cherry'];

// Check if all elements have more than 3 characters
$result = array_all($array, fn($value) => strlen($value) > 3);
var_dump($result);  // Output: bool(true)

// Check if all elements start with 'a'
$result = array_all($array, fn($value) => str_starts_with($value, 'a'));
var_dump($result);  // Output: bool(false)
?>
    


2. array_any

The array_any function checks if at least one element in the array satisfies the given callback condition. If any element meets the condition, array_any returns true; otherwise, it returns false. This is useful when only one match is required. 
 
Syntax:


array_any(array $array, callable $callback): mixed
    

Example:


<?php
$array = ['apple', 'banana', 'cherry'];

// Check if any element has more than 5 characters
$result = array_any($array, fn($value) => strlen($value) > 5);
var_dump($result);  // Output: bool(true)

// Check if any element starts with 'c'
$result = array_any($array, fn($value) => str_starts_with($value, 'c'));
var_dump($result);  // Output: bool(true)
?>
    

 
3. array_find

The array_find function returns the first element that satisfies the callback condition. If no element meets the condition, it returns null. This is useful for finding specific values without iterating through the entire array.  
 
Syntax:


array_find(array $array, callable $callback): mixed
    

Example:


<?php
$array = ['apple', 'banana', 'cherry'];

// Find the first element with more than 5 characters
$result = array_find($array, fn($value) => strlen($value) > 5);
var_dump($result);  // Output: string(6) "banana"

// Find the first element that starts with 'c'
$result = array_find($array, fn($value) => str_starts_with($value, 'c'));
var_dump($result);  // Output: string(6) "cherry"
?>
    


 
4. array_find_key

The array_find_key function returns the key of the first element that satisfies the callback condition. If no element meets the condition, it returns null. This is particularly useful for retrieving keys based on specific value conditions. 
 
 
Syntax:


array_find_key(array $array, callable $callback): mixed
    

Example:


<?php
$array = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];

// Find the key of the first element with more than 5 characters
$result = array_find_key($array, fn($value) => strlen($value) > 5);
var_dump($result);  // Output: string(1) "b"

// Find the key of the first element that starts with 'c'
$result = array_find_key($array, fn($value) => str_starts_with($value, 'c'));
var_dump($result);  // Output: string(1) "c"
?>
    


Instantiating Classes Without Parentheses for Immediate Method Calls  

In PHP, it’s common to create an instance of a class and call a method or access a property on that instance immediately. However, until PHP 8.4, you were required to wrap the instantiation in parentheses, which could make the code feel a bit cluttered. 
 
For example: 
// Before PHP 8.4 


<?php
$session = (new Session())->start()->set('user', 'John Doe');
?>
    


 

Simplified Syntax in PHP 8.4 

PHP 8.4 simplifies this syntax by allowing you to omit the parentheses. This allows for cleaner and more intuitive code, especially when chaining methods on a newly created instance.

For example:
 // In PHP 8.4 


<?php
$session = new Session()->start()->set('user', 'John Doe');
?>
    

 


Asymmetric Property Visibility 

PHP 8.4 introduces asymmetric property visibility, allowing separate control over reading and setting a property. You can define a property to be publicly readable but only writable within the class or by child classes, enhancing data encapsulation. 

Example:
Here’s a class where the property $name can be read publicly but set only within the class itself:


<?php
class User { 

    public private(set) string $name; 

    public function __construct(string $name) { 
        $this->name = $name; // Allowed since it's within the class 
    }   

    public function changeName(string $newName) { 
        $this->name = $newName; // Also allowed within the class 
    } 
} 
  
$user = new User("Alice"); 
echo $user->name;    // Outputs: Alice (public read access)   

$user->name = "Bob"; // Error: Cannot modify due to private(set)
?>
    

 


Key Points:

  • public private(set): $name is readable publicly but writable only within the class.

  • Benefits: Controlled modification of properties, preventing unintended writes from outside.

 

HTML5 Parsing and Serialization

PHP has introduced support for HTML5 parsing and serialization with the release of the DOM\HTMLDocument class, a significant update addressing compatibility issues with modern HTML standards. PHP’s \DOMDocument class originally relied on libxml2, which only supports HTML4.01, leading to multiple parsing errors and incorrect document structures when handling HTML5 content.
 
The HTML5 parser update, implemented by Niels Dossche, seamlessly integrates into the DOM extension, enabling PHP to handle HTML5's extended tag set and updated parsing rules without breaking compatibility with legacy HTML4 documents.

The DOM\HTMLDocument class leverages Lexbor, a spec-compliant, high-performance HTML5 parser. Lexbor's integration within PHP allows for accurate parsing and serialization of HTML5 content, addressing long-standing limitations, such as issues with semantic tags and JavaScript literals embedded within HTML. To maintain backward compatibility, the existing \DOMDocument class remains unchanged, while the DOM\HTMLDocument class offers HTML5 support. This addition aligns PHP’s DOM extension with modern web standards, enhancing its utility in web development.

 

Conclusion

The PHP 8.4 release is expected to be an essential turning point in the development of PHP. PHP 8.4's improved features, which are designed to improve security, performance, and the developer experience overall, will help developers to create applications more quickly and robustly. This upgrade demonstrates PHP's dedication to satisfying the demands of today's developers and enterprises, as it remains an essential part of online development.

Akshay Maradiya

Software Developer

One-stop solution for next-gen tech.

Frequently Asked Questions

Still have Questions?

Let’s Talk

1. What are the main features of PHP 8.4 release?

arrow

2. When is PHP 8.4 going to be available?

arrow

3. How will my development process be improved by PHP 8.4?

arrow

4. What is the difference between PHP 8.4 and earlier PHP versions?

arrow

5. Is it easy to update to PHP 8.4?

arrow