Exciting Updates and Features in PHP 8.4

Exciting Updates and Features in PHP 8.4

Yeasir Arafat Yeasir Arafat | 3 min read
6 hours ago

PHP 8.4, expected to be released on November 21, 2024, brings a treasure trove of enhancements and new features aimed at improving the developer experience and expanding the language's capabilities. Here's a rundown on some of the key features you can look forward to:

Property Hooks

Property Hooks allow custom behaviors to be defined when class properties are accessed or modified. This effectively reduces the reliance on boilerplate getter and setter methods. For instance, specific logic can be executed upon reading or writing a property value.

<?php
class Product {
    private float $price;

    public function getPrice(): float {
        echo "Getting price: ";
        return $this->price;
    }

    public function setPrice(float $price): void {
        if ($price < 0) {
            throw new InvalidArgumentException("Price cannot be negative");
        }
        echo "Setting price: ";
        $this->price = $price;
    }
}

$product = new Product();
$product->price = 99.99; // Output: Setting price: 
echo $product->price; // Output: Getting price: 99.99

Asymmetric Visibility

This feature allows developers to assign different visibility levels for reading and writing class properties, promoting better encapsulation. A property could be publicly readable but writable only within the class.

<?php
class BankAccount {
    public int $accountNumber;
    private float $balance;

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

    public function getBalance(): float {
        return $this->balance;
    }

    protected function setBalance(float $amount): void {
        if ($amount < 0) {
            throw new InvalidArgumentException("Balance cannot be negative");
        }
        $this->balance = $amount;
    }

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

$account = new BankAccount(123456, 500.00);
echo $account->getBalance(); // Output: 500.00
$account->deposit(100.00);
echo $account->getBalance(); // Output: 600.00

Method Chaining Without Parentheses

PHP 8.4 simplifies object instantiation and method chaining by removing the need for parentheses when no constructor arguments are provided.

<?php
class Car {
    private int $speed = 0;

    public function accelerate(): self {
        $this->speed += 10;
        echo "Accelerating. Speed is now: {$this->speed}\n";
        return $this;
    }

    public function brake(): self {
        $this->speed = max(0, $this->speed - 10);
        echo "Braking. Speed is now: {$this->speed}\n";
        return $this;
    }
}

$car = new Car->accelerate()->accelerate()->brake();

New Array Functions

New functions such as array_find(), array_find_key(), array_any(), and array_all() provide better ways to manipulate arrays.

1. array_find()

This function finds the first element satisfying a specified condition.

<?php
$numbers = [1, 3, 5, 8, 10];
$firstEven = array_find($numbers, fn($num) => $num % 2 === 0);
echo $firstEven; // Output: 8
2. array_find_key()

This function finds the key of the first element meeting a specific condition.

<?php
$items = [
    'apple' => 'fruit',
    'banana' => 'fruit'
];
$firstFruitKey = array_find_key($items, fn($item) => $item === 'fruit');
echo $firstFruitKey; // Output: apple
3. array_any()

This function checks if any elements satisfy the given condition.

<?php
$numbers = [1, 3, 5, 8, 10];
$hasEven = array_any($numbers, fn($num) => $num % 2 === 0);
echo $hasEven ? 'true' : 'false'; // Output: true
4. array_all()

Checks if all elements meet the specified condition.

<?php
$numbers = [2, 4, 6, 8];
$allEven = array_all($numbers, fn($num) => $num % 2 === 0);
echo $allEven ? 'true' : 'false'; // Output: true

HTML5 Support in DOM Extension

The DOM extension now includes a DomHTMLDocument class to improve HTML5 document handling.

<?php
$htmlContent = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample HTML5 Document</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <p>This is a sample paragraph.</p>
</body>
</html>
HTML;

$doc = new DomHTMLDocument();
$doc->loadHTML($htmlContent);
echo $doc->saveHTML();

Multibyte String Trimming Functions

New functions like mb_trim(), mb_ltrim(), and mb_rtrim() enhance string manipulation for multibyte character encodings.

<?php
$sampleText = " \tこんにちは、世界!  ";
$trimmedText = mb_trim($sampleText);
echo "Trimmed: '$trimmedText'\n";

Deprecation of Implicit Nullable Parameters

PHP 8.4 requires explicit marking of nullable parameters using a ? syntax, deprecating the earlier practice of implicitly allowing null values.

<?php
function greet(?string $name = null) {
    if ($name === null) {
        return "Hello, guest!";
    }
    return "Hello, $name!";
}

echo greet();        // Output: Hello, guest!
echo greet("Alice"); // Output: Hello, Alice!

JIT Improvements 🚀

Enhancements in Just-In-Time (JIT) compilation are set to boost PHP's performance.

In summary, PHP 8.4 brings a host of exciting updates designed to streamline coding, improve performance, and align with modern development trends. Which feature are you excited about the most?

Discussions

Login to Post Comments
No Comments Posted