Exploring PHP 8.4: New Features and Deprecations

Share

PHP 8.4 has been officially released, introducing a host of new features, performance enhancements, and deprecations. This article delves into the most significant updates, helping developers understand and leverage the latest improvements in their projects. If you work with state-driven logic, our guide to FSM transition states in PHP is a related deep dive.

Key Features in PHP 8.4

1. Property Hooks

PHP 8.4 introduces property hooks, allowing developers to define get and set behaviors directly within class properties. This feature reduces boilerplate code and enhances encapsulation.

class User {
private string $email;
public string $emailAddress {
get {
return $this->email;
}
set {
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw new ValueError('Invalid email address');
}
$this->email = $value;
}
}
}
$user = new User();
$user->emailAddress = 'test@example.com'; // Valid
$user->emailAddress = 'invalid-email'; // Throws ValueError

In this example, the $emailAddress property includes custom get and set hooks to manage the internal $email property, ensuring only valid email addresses are assigned.

2. Asymmetric Visibility

With asymmetric visibility, PHP 8.4 allows different access levels for reading and writing class properties. This provides finer control over property accessibility.

class Account {
public private(set) float $balance;
public function __construct(float $initialBalance) {
$this->balance = $initialBalance;
}
public function deposit(float $amount): void {
$this->balance += $amount;
}
}
$account = new Account(100.0);
echo $account->balance; // Outputs: 100
$account->deposit(50.0);
echo $account->balance; // Outputs: 150
$account->balance = 200.0; // Error: Cannot modify private(set) property

Here, the $balance property can be read publicly but modified only within the class, ensuring controlled updates.

3. Lazy Objects

PHP 8.4 introduces lazy objects, enabling the creation of class instances that are initialized only when needed. This can improve performance by deferring resource-intensive operations until they are actually required.

use LazyObjectLazyObject;
class ExpensiveResource {
public function __construct() {
// Simulate a costly initialization process
sleep(5);
}
public function performAction() {
return "Action performed.";
}
}
$lazyResource = LazyObject::create(ExpensiveResource::class);
// The ExpensiveResource is not initialized yet
echo "Lazy object created.n";
// Now we access a method, triggering initialization
echo $lazyResource->performAction(); // Outputs: Action performed.

In this scenario, the ExpensiveResource object is only initialized when performAction is called, optimizing resource usage.

4. New Array Functions

PHP 8.4 enhances array manipulation with new functions: array_find, array_find_key, array_any, and array_all.

$numbers = [1, 2, 3, 4, 5];
// Find the first even number
$firstEven = array_find($numbers, fn($n) => $n % 2 === 0);
echo $firstEven; // Outputs: 2
// Check if any number is greater than 4
$hasGreaterThanFour = array_any($numbers, fn($n) => $n > 4);
var_export($hasGreaterThanFour); // Outputs: true
// Ensure all numbers are positive
$allPositive = array_all($numbers, fn($n) => $n > 0);
var_export($allPositive); // Outputs: true

These functions provide more expressive and concise ways to work with arrays.

5. HTML5-Compliant DOM Parsing

The DOM extension in PHP 8.4 now includes an HTML5-compliant parser, improving support for modern HTML standards.

use DOMHTMLDocument;
$html = '<!DOCTYPE html><html><body><p>Test</p></body></html>';
$doc = new HTMLDocument();
$doc->loadHTML($html);
echo $doc->saveHTML(); // Outputs the well-formed HTML

This enhancement ensures better handling of HTML5 documents within PHP applications.

Notable Deprecations in PHP 8.4

As PHP evolves, certain features are deprecated to encourage best practices and maintain the language’s robustness. Key deprecations in PHP 8.4 include:

1. Implicitly Nullable Parameter Types

Implicitly nullable parameter types are now deprecated. Developers must explicitly declare nullable types using the ? syntax.

// Deprecated
function process(?string $data = null) {
// ...
}
// Recommended
function process(?string $data = null) {
// ...
}

This change promotes clarity and reduces potential ambiguities in function signatures.

2. Deprecation of Certain Extensions

The following extensions have been unbundled from the core and moved to PECL:

  • IMAP
  • OCI8
  • PDO_OCI
  • Pspell

Developers relying on these extensions should install them separately via PECL.

3. Deprecated Functions and Constants

Several functions and constants are deprecated in PHP 8.4:

  • mysqli_ping() and mysqli::ping()
  • mysqli_refresh()
  • mysqli_kill()
  • E_STRICT constant
  • strtok()
  • lcg_value()

Wrapping Up

PHP 8.4 brings an exciting array of features, from property hooks and asymmetric visibility to lazy objects and enhanced array functions, empowering developers to write more efficient, maintainable, and modern code. Pairing these new features with consistent PHP Standard Recommendations (PSR) keeps your codebase clean as it grows.

As you explore these new capabilities, staying updated with best practices and adapting to deprecations will ensure your projects remain robust and future-proof.

At LN Webworks, we specialize in crafting custom web solutions with the latest technologies, including PHP and Drupal. Whether you’re looking to upgrade your existing application or build something new, our expert team is here to help you leverage the power of PHP 8.4 to deliver exceptional digital experiences.

Sunil
The Author
Sunil

Web Developer

Read More Blogs

Illustration comparing a custom CRM and an off-the-shelf CRM, showing a business professional choosing between a tailored CRM solution and a packaged CRM software. Other, SaaS Development

SaaS CRMs win on speed. Custom wins on fit and ownership. This isn’t a pitch for either one. Every early-stage SaaS company hits this decision within the first year, usually right after the founder realizes a spreadsheet isn’t a CRM.  The default answer is almost always a SaaS CRM: HubSpot, Salesforce, Zoho, sign up in […]

Illustration of a modernization readiness assessment highlighting business alignment, technology assessment, process optimization, data integration, people and skills, risk and compliance, and a roadmap for successful digital transformation Other

Most “audits” and “assessments” promise clarity but deliver a sales deck with language that lacks clarity. You book the call expecting evidence about your specific platform, and what shows up is a generic pitch for whichever package is easiest for the firm to sell.  That’s the actual reason process transparency matters here, not because a […]

LN Webworks illustration of the BAT-BMS Bluetooth exploit, app ban, and access-control review process Other

In late June and early July, videos started circulating on Instagram of people walking up to moving e-rickshaws, tapping a phone, and watching the vehicle lose power mid-ride.  It spread as a prank trend before anyone fully understood the mechanism. Drivers in Patna (India) reported it first, assuming mechanical failure, until investigators traced it to […]

LN Webworks Logo
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.