Web Development

Exploring PHP 8.4: Key Features, Enhancements, and Performance Upgrades

PHP 8.4 introduces an array of powerful features, including property hooks, asymmetric visibility, new array functions, and performance optimizations. From stricter type safety to enhanced developer tools, this update continues to modernize PHP while boosting productivity and code quality. Dive into the details to explore what’s new!
Avatar photo
by Furkan OZTURK
Full-stack Developer
Published: Jan 6, 2025 10:07
Modified: Jan 26, 2025 12:39

PHP 8.4, released on November 21, 2024, introduces several features and improvements aimed at enhancing developer productivity and code quality. Here’s an overview of the most notable additions:

Property Hooks

Property hooks allow developers to define custom behavior when accessing or modifying class properties, eliminating the need for separate getter and setter methods.

Example:

class User {
    private string $firstName;
    private string $lastName;

    public function __construct(string $firstName, string $lastName) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

    public string $fullName {
        get => $this->firstName . ' ' . $this->lastName;
        set => [$this->firstName, $this->lastName] = explode(' ', $value, 2);
    }
}

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

$user->fullName = 'Jane Smith';
echo $user->fullName; // Output: Jane Smith

Asymmetric Visibility

PHP 8.4 introduces the ability to assign different visibility levels for property getters and setters, enhancing encapsulation.

Example:

class BankAccount {
    public private(set) float $balance;

    public function __construct(float $initialBalance) {
        $this->balance = $initialBalance;
    }

    public function deposit(float $amount): void {
        $this->balance += $amount;
    }
}

$account = new BankAccount(100.0);
echo $account->balance; // Output: 100

$account->deposit(50.0);
echo $account->balance; // Output: 150

// The following line will cause an error:
// $account->balance = 200.0;

New Array Functions

PHP 8.4 adds functions like array_find(), array_any(), and array_all() to simplify common array operations.

Example:

$numbers = [1, 2, 3, 4, 5];

// Find the first even number
$firstEven = array_find($numbers, fn($n) => $n % 2 === 0);
echo $firstEven; // Output: 2

// Check if any number is greater than 4
$hasBigNumber = array_any($numbers, fn($n) => $n > 4);
var_dump($hasBigNumber); // Output: bool(true)

// Check if all numbers are positive
$allPositive = array_all($numbers, fn($n) => $n > 0);
var_dump($allPositive); // Output: bool(true)

Simplified Object Instantiation

Developers can now instantiate an object and immediately call a method on it without extra parentheses. (This is a personal one 😬 which I’ve been waiting for a long time)

Example:

class Logger {
    public function log(string $message): void {
        echo $message;
    }
}

// Create an object and call a method in one step
new Logger()->log('Logging a message'); // Output: Logging a message

Lazy Objects

Lazy objects allow the deferral of object creation until they are actually used, optimizing resource utilization.

Example:

class ExpensiveResource {
    public function __construct() {
        // Simulate a time-consuming setup
        sleep(2);
    }

    public function doWork(): void {
        echo 'Working...';
    }
}

// Use a lazy object to delay creation
$initializer = fn() => new ExpensiveResource();
$reflector = new ReflectionClass(ExpensiveResource::class);
$resource = $reflector->newLazyProxy($initializer);

// The object isn't created yet
$resource->doWork(); // Now the object is created and "Working..." is printed

HTML5 Parsing Support

The DOM extension in PHP 8.4 now includes a new DomHTMLDocument class that fully supports HTML5 parsing.

Example:

$html = "html content...";
$doc = new DomHTMLDocument();
$doc->loadHTML($html);
echo $doc->saveHTML();

Multibyte Trim Functions

PHP 8.4 introduces multibyte string trim functions: mb_trim(), mb_ltrim(), and mb_rtrim().

Example:

// output:
// string(5) "Scott"
var_dump(mb_trim(" Scott "));

// output:
// string(9) "Scott "
var_dump(mb_ltrim(" Scott "));

// output:
// string(8) " Scott"
var_dump(mb_rtrim(" Scott "));

New Rounding Modes in round() Function

PHP 8.4 introduces additional rounding modes for the round() function, giving developers more control over how floating-point numbers are rounded. The new modes include half-up, half-down, half-even, and half-odd.

echo round(2.5, 0, PHP_ROUND_HALF_UP);    // Output: 3
echo round(2.5, 0, PHP_ROUND_HALF_DOWN);  // Output: 2
echo round(2.5, 0, PHP_ROUND_HALF_EVEN);  // Output: 2
echo round(2.5, 0, PHP_ROUND_HALF_ODD);   // Output: 3

Improved Performance

PHP 8.4 includes several internal optimizations to boost performance, including:

• Improvements to JIT (Just-In-Time) Compilation: Enhancements to JIT compilation reduce overhead for repetitive tasks and improve execution speed for heavy computational operations.

• Refinements in Garbage Collection: The updated garbage collector reduces memory usage, making it more efficient for long-running applications.

Named Arguments for Closures

Named arguments, already available for regular functions and methods, can now be used with closures in PHP 8.4.

$closure = fn(string $name, int $age) => "$name is $age years old";

echo $closure(name: "Alice", age: 30); // Output: Alice is 30 years old

Conclusion

PHP 8.4 represents a significant step forward for the language, with its focus on developer ergonomics, performance, and stricter type safety. These improvements not only streamline everyday coding tasks but also make PHP more competitive as a modern programming language. As developers adopt PHP 8.4, they can expect to write more expressive, robust, and performant code…