A Look at What’s Coming to PHP 8.4
Laravel

A Look at What’s Coming to PHP 8.4

A Look at What’s Coming to PHP 8.4

The PHP team has recently released PHP 8.4, introducing a variety of new features and enhancements aimed at improving the developer experience. This article explores the significant updates included in this version, such as property hooks, new array find functions, and class instantiation without extra parentheses, among others. These changes are designed to streamline coding practices and enhance the performance of PHP applications.

New Array Find Functions

One of the most notable additions in PHP 8.4 is the introduction of new array find functions. These functions simplify the process of searching through arrays, making it easier for developers to retrieve specific values or keys. The new functions include:

  • array_find(): Finds the first value in an array that satisfies a given condition.
  • array_find_key(): Retrieves the key of the first element that matches a specific condition.
  • array_any(): Checks if any elements in an array satisfy a given condition.
  • array_all(): Verifies if all elements in an array meet a specified condition.

These functions enhance the functionality of PHP’s array handling capabilities, making it easier for developers to work with complex data structures.

Property Hooks

Inspired by languages like Kotlin, C#, and Swift, PHP 8.4 introduces property hooks, which allow developers to define custom logic for property access and updates. This feature aims to reduce boilerplate code associated with property getters and setters. The syntax for property hooks includes two variants that resemble short and multi-line closures. Here’s an example:

        class User implements Named {
            private bool $isModified = false;

            public function __construct(private string $first, private string $last) {}

            public string $fullName {
                get => $this->first . " " . $this->last;
                set {
                    [$this->first, $this->last] = explode(' ', $value, 2);
                    $this->isModified = true;
                }
            }
        }
    

This feature allows for more intuitive and cleaner code when managing object properties, enhancing the overall readability and maintainability of PHP applications.

Class Instantiation Without Extra Parenthesis

Another significant change in PHP 8.4 is the ability to instantiate classes without requiring extra parentheses. Previously, developers had to wrap the instantiation in parentheses to access class members, which could lead to syntax errors. The new syntax allows for a more streamlined approach:

        // Previous syntax
        $request = (new Request())->withMethod('GET')->withUri('/hello-world');

        // New syntax in PHP 8.4
        $request = new Request()->withMethod('GET')->withUri('/hello-world');
    

This update simplifies the code and aligns PHP more closely with other C-based languages, making it easier for developers transitioning from languages like Java and C#.

Creating DateTime from a Unix Timestamp

PHP 8.4 enhances the DateTime functionality by introducing the createFromTimestamp() method, which allows for the creation of DateTime objects directly from Unix timestamps, including those with microseconds. This method streamlines the process of handling date and time in applications:

        $dt = DateTimeImmutable::createFromTimestamp(1718337072);
        echo $dt->format('Y-m-d'); // Outputs: 2024-06-14

        $dt = DateTimeImmutable::createFromTimestamp(1718337072.432);
        echo $dt->format('Y-m-d h:i:s.u'); // Outputs: 2024-06-14 03:51:12.432000
    

This improvement makes it much more convenient for developers to work with timestamps, enhancing the overall functionality of date and time manipulation in PHP.

New mb_ Functions

PHP 8.4 also introduces several new multi-byte string functions, enhancing support for internationalization and text processing. The new functions include:

  • mb_trim(): Trims whitespace from the beginning and end of a string.
  • mb_ltrim(): Trims whitespace from the beginning of a string.
  • mb_rtrim(): Trims whitespace from the end of a string.
  • mb_ucfirst(): Converts the first character of a string to uppercase.
  • mb_lcfirst(): Converts the first character of a string to lowercase.

These functions carry the same arguments as their non-multi-byte counterparts, making them easy to integrate into existing codebases.

Asymmetric Property Visibility

PHP 8.4 introduces the concept of asymmetric property visibility, allowing developers to set different visibility levels for reading and writing properties. This feature enhances encapsulation and provides more control over how properties are accessed and modified. Here’s an example:

        class Book {
            public function __construct(
                public private(set) string $title,
                public protected(set) string $author,
                protected private(set) int $pubYear,
            ) {}
        }

        class SpecialBook extends Book {
            public function update(string $author, int $year): void {
                $this->author = $author; // OK
                $this->pubYear = $year; // Fatal Error
            }
        }
        
        $b = new Book('How to PHP', 'Peter H. Peterson', 2024);
        echo $b->title; // Outputs: How to PHP
        echo $b->author; // Outputs: Peter H. Peterson
        echo $b->pubYear; // Fatal Error
    

This feature allows for greater flexibility in class design, enabling developers to enforce stricter access controls on class properties.

Laravel Herd Support

If you are looking for an easy way to start using PHP 8.4, Laravel Herd already includes support for this version. Laravel Herd simplifies the setup process, allowing developers to switch to PHP 8.4 effortlessly. This integration makes it easier to explore and utilize the new features introduced in PHP 8.4.

Additional Resources

To fully leverage the new features in PHP 8.4, developers are encouraged to review the following resources:

Frequently Asked Questions

What are the new array find functions introduced in PHP 8.4?

PHP 8.4 introduces new array find functions including array_find(), array_find_key(), array_any(), and array_all(), which simplify the process of searching through arrays.

How do property hooks improve PHP 8.4?

Property hooks in PHP 8.4 allow developers to define custom logic for property access and updates, reducing boilerplate code associated with getters and setters.

What is asymmetric property visibility in PHP 8.4?

Asymmetric property visibility allows developers to set different visibility levels for reading and writing properties in a class, enhancing encapsulation and control over property access.

Call To Action

Stay ahead in your development journey by exploring the new features of PHP 8.4. Upgrade your projects today and leverage these enhancements for better performance and cleaner code.

Note: PHP 8.4 brings significant improvements that enhance developer productivity and code quality. Embrace these updates to optimize your PHP applications.

Disclaimer: Tech Nxt provides news and information for general awareness purposes only. While we strive for accuracy, we do not guarantee the completeness or reliability of any content. Opinions expressed are those of the authors and not necessarily of Tech Nxt. We are not liable for any actions taken based on the information published. Content may be updated or changed without prior notice.