PHP 8.4: All You Need to Know (Features, Improvements and How to Upgrade)

 PHP 8.4: All You Need to Know (Features, Improvements and How to Upgrade)


As the PHP project continues its tradition of releasing a new major or minor version towards the end of each year, they’ve released the latest version, i.e., PHP 8.4.

It released today November 21st, 2024, with significantly improved features and a comprehensive list of deprecations/removals.

Let’s find out what the latest PHP 8.4 features are and how you can upgrade from PHP 8.3 to 8.4. You will also learn how to create a staging environment for free with Cloudways to test the upgrade before applying it.

    Overview PHP 8.4

    All feature proposals and changes included in the PHP 8.4 version were discussed and approved by the PHP internals team.

    Earlier this year, an RFC introduced changes to the PHP release cycle, which came into effect in June.

    PHP 8.4 Release Date Timeline

    The updated release schedule adjusted the beginning of the cycle and shortened the release candidate phase to four versions while keeping the same annual release date.

    This change provided more time for discussions on new features and recognized that the last two release candidates in previous cycles often had minimal changes or none at all.

    DateMilestone
    July 4, 2024Alpha Release 1
    July 18, 2024Alpha Release 2
    August 1, 2024Alpha Release 3 (Skipped)
    August 1, 2024Alpha Release 4
    August 13, 2024Feature Freeze
    August 15, 2024Beta Release 1 (Skipped)
    August 15, 2024Beta Release 2 (Skipped)
    August 15, 2024Beta Release 3
    August 29, 2024Beta Release 4
    September 12, 2024Beta Release 5
    September 26, 2024Release Candidate 1
    October 10, 2024Release Candidate 2
    October 24, 2024Release Candidate 3
    November 7, 2024Release Candidate 4
    November 21, 2024General Availability Release

     

    PHP 8.4 Features

    The latest version of PHP has several new features and deprecations, addressing some challenges that developers have been facing. Let’s find out the key improved features of PHP 8.4:

    Property Hooks

    PHP 8.4 introduces one of the most significant advancements in modern PHP: property hooks, which greatly reduce the need for boilerplate code.

    Property hooks let you define logic for getting and setting properties directly within the property itself, which eliminates the need for separate getter and setter methods.

    For example, you can implement hooks for either the getter or setter independently, but it’s recommended to implement both if one is defined.

    Here is an example from the RFC:

    1. class Book
    2. {
    3. private string $title;
    4. private string $author;
    5. public function __construct(string $title, string $author) {
    6. $this->title = $title;
    7. $this->author = $author;
    8. }
    9. // "Setting" book title and author
    10. public function setTitle(string $title): void {
    11. $this->title = $title;
    12. }
    13. public function setAuthor(string $author): void {
    14. $this->author = $author;
    15. }
    16. // "Getting" book title and author
    17. public function getTitle(): string {
    18. return $this->title;
    19. }
    20. public function getAuthor(): string {
    21. return $this->author;
    22. }
    23. } // End of class
    24. // Create a new book
    25. $book = new Book('1984', 'George Orwell');
    26. print $book->getTitle() . ' by ' . $book->getAuthor(); // Prints "1984 by George Orwell"
    27. // Change book details
    28. $book->setTitle('Animal Farm');
    29. $book->setAuthor('George Orwell');
    30. print $book->getTitle() . ' by ' . $book->getAuthor(); // Prints "Animal Farm by George Orwell"

    This brings a whole new approach to PHP object-oriented programming (OOP).

    Asymmetric Visibility

    Another powerful feature introduced in PHP 8.4 is asymmetric visibility, which addresses limitations in “readonly” properties introduced in earlier versions.

    Sometimes, an object needs to behave more like a data structure, which can be easily modified while maintaining internal validity.

    Asymmetric Visibility resolves some of these challenges. It brings the concept of different visibility options for reading and writing a property. For example, you can make a property readable by everyone but restrict its modification to specific parts of your codebase.

    1. class UserProfile {
    2. // Public read access, but private write access
    3. public string $name;
    4. // Public read access, but protected write access
    5. public int $age;
    6. // Constructor to initialize properties
    7. public function __construct(string $name, int $age) {
    8. $this->name = $name;
    9. $this->age = $age;
    10. }
    11. // A method to update the age, which is allowed internally but not from outside
    12. protected function updateAge(int $newAge): void {
    13. if ($newAge >= 18) {
    14. $this->age = $newAge;
    15. } else {
    16. echo "Age must be 18 or older.";
    17. }
    18. }
    19. }
    20. $user = new UserProfile("John Doe", 30);
    21. // Publicly readable
    22. echo $user->name; // Outputs: John Doe
    23. echo $user->age; // Outputs: 30
    24. // You cannot modify the properties directly from outside the class:
    25. $user->name = "Jane Doe"; // This works because it's public
    26. $user->age = 25; // This would fail if asymmetric visibility was in place
    27. // However, internal write access is possible via methods
    28. $user->updateAge(32); // Valid, updates age

    In the above example:

    • The property $name is public for both reading and writing but could be configured with asymmetric visibility to make it writable only by internal code.
    • The property $age is public for reading but protected for writing, meaning external code can’t modify it directly. Instead, it would need to be modified through an internal method like updateAge.

    This new PHP 8.4 feature complements earlier enhancements Property Hooks, which introduced the ability to define property visibility within interfaces.

    Combined, these two features provide developers more flexibility and control in manipulating objects to build correct data types.

    MyClass()->method() Without Parentheses

    Previously, when creating a new instance and chaining methods, you had to wrap the invocation in parentheses like this:

    1. $user = (new User())->getName()->getEmail();

    In PHP 8.4, you can now omit the parentheses, making it cleaner and more intuitive:

    1. $user = new User()->getName()->getEmail();

    While it might seem like a small adjustment, removing just two brackets greatly improves readability and makes the code easier to debug.

    HTML5 Support

    PHP 8.4 introduces the new \Dom\HTMLDocument class, which offers efficient HTML parsing capabilities. The older \DOMDocument class remains available for backward compatibility.

    1. $doc = \Dom\HTMLDocument::createFromString($contents);

    For developers working with HTML parsing or construction via the DOM extension, this release brings several innovative features that are focused on delivering solid results, along with strong support for HTML5.

    JIT Changes

    The most important compatibility-breaking change in PHP 8.4 is the JIT (Just-In-Time compiler).

    In the previous versions of PHP, you could disable JIT by setting opcache.jit_buffer_size to 0. However, in PHP 8.4, disabling JIT is now more easier:

    1. opcache.jit=disable
    2. opcache.jit_buffer_size=64m

    Users who previously relied on the opcache.jit_buffer_size parameter without explicitly using opcache.jit will need to adjust their configurations. Add opcache.jit=tracing to enable the JIT.

    The changes and improvements made to JIT will make PHP 8.4 faster in some scenarios and it is expected to consume less memory.

    Lazy Objects

    PHP 8.4 also introduces native support for lazy objects, a widely used pattern in frameworks for creating proxy objects.

    1. $initializer = static function (MyClass $proxy): MyClass {
    2. return new MyClass(123);
    3. };
    4. $reflector = new ReflectionClass(MyClass::class);
    5. $object = $reflector->newLazyProxy($initializer);

    Exit and Die as Functions

    In PHP, exit (and its alias die) has always been somewhat unusual: it could be used both as a keyword like this: exit;, and as a function: exit(0);.

    However, the function variant wasn’t truly a function and had several limitations:

    • It didn’t support named arguments.
    • It couldn’t be used as a callable.
    • It ignored strict_types.
    • It didn’t follow the usual type-juggling behavior.

    With PHP 8.4, exit() and die() are now properly treated as functions, and all of these issues have been resolved.

    Note that the keyword variant without parentheses still behaves the same way as before.

    Multibyte Trim Functions

    Another long-awaited feature in PHP 8.4 is the multibyte support for trim functions, and it has been introduced with the following new functions:

    • mb_trim()
    • mb_ltrim()
    • mb_rtrim()

    Similar to the traditional trim() function in PHP, mb_trim() removes whitespace and certain special characters, such as line feeds, from both ends of a string that may contain multibyte characters.

    The other functions, mb_ltrim() and mb_rtrim(), trim the left and right ends of the string, respectively.

    PHP 8.4 Deprecations

    Each new release of PHP includes deprecations and removals of less popular or outdated features. PHP 8.4 is no exception, introducing several deprecations aimed at improving consistency and future-proofing the language.

    Implicit Nullable Types

    Until PHP 8.3, typed variables with a default null value could implicitly be treated as nullable. For example:

    1. function bar(T1 $a, ?T2 $b = null, T3 $c) {}

    Even though this worked, it lacked explicit clarity. But with PHP 8.4, implicit nullable types are deprecated, requiring developers to explicitly declare nullable types using the ? syntax.

    Deprecation of GET/POST Sessions

    Web applications often track user sessions using cookies. However, PHP also allowed sessions to be managed through GET and POST parameters by disabling the session.use_only_cookies setting and enabling session.use_trans_sid.

    These settings were primarily used for legacy browsers without cookie support. By default:

    • session.use_only_cookies is enabled
    • session.use_trans_sid is disabled

    In PHP 8.4, a deprecation warning will be triggered if either of these settings is changed from their default values.

    More Deprecations in PHP 8.4

    Here is a list of all the deprecations or removals in PHP 8.4:

    • Formally deprecate soft-deprecated DOMDocument and DOMEntity properties.
    • Deprecate E_STRICT constant.
    • Deprecate strtok().
    • Deprecate returning non-string values from a user output handler.
    • Deprecate producing output in a user output handler.
    • Deprecate file_put_contents() with $data as an array.
    • Deprecate mysqli_ping() and mysqli::ping().
    • Deprecate mysqli_refresh().
    • Deprecate mysqli_kill().
    • Deprecate the second parameter to mysqli_store_result().
    • Removed DOMImplementation::getFeature($feature, $version).
    • Deprecate DOM_PHP_ERR constant.
    • Deprecate the “S” tag in unserialize().
    • Deprecate session.sid_length and session.sid_bits_per_character.
    • Deprecate SplFixedArray::__wakeup().
    • Deprecate lcg_value().
    • Deprecate uniqid().
    • Deprecate md5(), sha1(), md5_file(), and sha1_file().
    • Deprecate passing E_USER_ERROR to trigger_error().
    • Deprecate using a single underscore (“_”) as a class name.
    • Deprecate SOAP_FUNCTIONS_ALL constant and passing it to SoapServer::addFunction().
    • Deprecate xml_set_object() and xml_set_*_handler() with string method names.
    • Deprecate passing null and false to dba_key_split().
    • Deprecate passing incorrect data types for options to ext/hash functions.
    • Deprecate constants SUNFUNCS_RET_STRING, SUNFUNCS_RET_DOUBLE, SUNFUNCS_RET_TIMESTAMP.
    • Deprecate proprietary CSV escaping mechanism.

    How to Upgrade to the Latest PHP 8.4 Version

    While it sounds technical, upgrading your WordPress website to the latest PHP version is a simple process.

    But before you begin:

    • Backup Your Website: This is crucial to ensure you can revert to a previous state if anything goes wrong.
    • Test in a Staging Environment: If possible, test the upgrade in a staging environment to minimize risks to your live site.

    With Cloudways, you can create a clone of your website to test it on the latest version.

    If the clone website works smoothly after upgrading to the latest PHP version, you can move ahead with updating your actual site. 

    This portion will list out the steps to create a clone website to test it under PHP 8.3 (currently the latest version of PHP on Cloudways).

    Clone a Website via Your Web Hosting Provider

    Fortunately, managed WordPress hosting solutions like Cloudways allow users to create their site’s duplicate without dealing with any complexities. Follow the steps below to create your website’s clone via Cloudways.

    • Click on Applications on your dashboard.
    • Locate the application you want to clone and click the 3 vertical dots next to it.
    • Select “Clone App/Create Staging” from the options.

    • Choose a server for the clone application and checkmark the option to create it as a staging site. Then, click “Continue.”

    • Wait for the system to check the requirements for your staging application.

    • After approximately 2 minutes, your cloned app will be ready.

    • Look for the “www” icon next to the server you selected, and click on the staging site.

    • Now, you are all set to experiment and make changes to the clone application.

    💡Note: Clone App and Create as Staging are different functionalities. Clicking Clone App will only clone your website. Whereas, Create as Staging will sync the live and staged applications to allow you to perform Push/Pull actions on both the replica and live versions.

    How to Upgrade to the Latest PHP Version on Cloudways

    You can easily upgrade your current PHP version to the latest version on Cloudways by following the steps below:

    • Login to the Cloudways Platform.
    • Click on Total Servers and select your server.

    • You’ll be redirected to the Server Management page.
    • Click Settings Packages > Packages.

    • Select PHP 8.3 from the drop-down menu.

    • Click Save.
    • That’s how easily you can upgrade your PHP version on Cloudways.

    Why Businesses and Agencies Need PHP 8.4?

    Any business that doesn’t stay up-to-date is setting itself up for failure. And staying updated includes your online presence.

    Upgrading to PHP 8.4 can a game-changer for business owners and agencies. With significant performance improvements, your websites and applications will load faster, providing a better user experience and potentially increasing conversion rates.

    More powerful security features offer better protection against vulnerabilities, ensuring your data and your customers’ data remain safe.

    ➕ By upgrading to PHP 8.4 on Cloudways, you can ensure your web applications stay ahead of the curve, delivering exceptional user experience while prioritizing security with new functionalities and streamlining development processes, enabling your team to deliver projects more efficiently and cost-effectively.

    Wrapping Up

    The release of PHP 8.4 is definitely exciting for developers. There are significant changes focused on solving dev challenges.

    Features like chaining new without parentheses make the code neater and easier for developers to debug – showing PHP’s commitment to make the technical staff’s experience better.

    If you’re considering transitioning to PHP 8.4, a thorough review of the documentation is recommended to ensure a smooth adaptation to the new features and changes.

    Comments