PHP 8.4: Simplified Coding, Enhanced Security, and Internationalization Features with Examples
PHP 8.4 introduces new features that simplify coding, improve security, and enhance support for internationalization. Below are key highlights with practical examples.
Property hooks allow you to define custom logic for reading and writing properties.
Example: Read-Only Property
class Circle {
public float $radius;
public float $area {
get {
return pi() * $this->radius ** 2;
}
}
public function __construct(float $radius) {
$this->radius = $radius;
}
}
$circle = new Circle(5);
echo $circle->area; // 78.5398...
// $circle->area = 100; // Error: Cannot set read-only property
This feature eliminates the need for explicit getter methods.
New functions like array_find and array_any simplify array operations.
Example: Finding an Element
$numbers = [1, 2, 3, 4, 5];
$firstEven = array_find($numbers, fn($num) => $num % 2 === 0);
echo $firstEven; // Outputs: 2
This function is more versatile compared to array_filter.
Functions like mb_ucfirst and mb_trim provide better support for Unicode strings.
Example: Capitalizing Unicode Strings
$text = "äpple";
echo mb_ucfirst($text); // Outputs: "Äpple"
These functions improve readability and reduce the need for custom implementations
The new \Dom\HTMLDocument class ensures compatibility with modern HTML5 structures.
Example: Parsing HTML5
$html = "<article><header>Header</header><p>Content</p></article>";
$doc = \Dom\HTMLDocument::createFromString($html);
echo $doc->saveHTML(); // Outputs: Properly formatted HTML5
The bcrypt hashing default cost is now 12, increasing the computational effort for brute-force attacks.
Example: Secure Password Hashing
$password = 'secure_password';
$hash = password_hash($password, PASSWORD_DEFAULT); // Default cost is now 12
echo $hash;
This change strengthens application security without requiring developer intervention.
PHP 8.4's features enhance developer productivity while ensuring compatibility with modern standards. Explore the official PHP documentation for more details