
PHP 8.4 is here, bringing with it a slew of new features and enhancements that promise to make development more efficient, secure, and enjoyable. From property hooks to new array functions, this update is packed with improvements that every PHP developer should be aware of. In this article, we shall dive into the most important changes introduced in PHP 8.4.
Property Hooks
Property hooks are one of the standout features in PHP 8.4. They allow developers to intercept property access operations like getting or setting a property value. This feature is similar to what other languages like Python offer through its __getattr__
and __setattr__
methods.
Property hooks in PHP 8.4 provide a powerful way to manage property access with greater control and flexibility. Here's an example of how you can use property hooks:
class Example {
private array $properties = [];
public function __get(string $name) {
if (array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
throw new Exception("Property {$name} does not exist");
}
public function __set(string $name, $value) {
// You can add validation or transformation logic here
$this->properties[$name] = $value;
}
}
$example = new Example();
$example->newProperty = "Hello, World!";
echo $example->newProperty; // Outputs: Hello, World!
In this example, the __get
and __set
magic methods are used to intercept attempts to access or modify properties that don't explicitly exist in the class. This allows for dynamic property management within your objects while maintaining encapsulation and control over data manipulation.
Benefits of Property Hooks
- Encapsulation: Property hooks provide better encapsulation by allowing developers to control how properties are accessed and modified.
- Validation: They enable validation logic directly within the property accessor methods.
- Lazy Loading: Developers can implement lazy loading for properties that may require expensive operations to initialise.
- Transformation: Automatically convert input data to a desired format (e.g., serialising arrays to JSON for storage).
- Computed Properties: Provide dynamic, computed values for properties based on other internal state or logic without actually storing the values.
- Interfacing with External Systems: Seamlessly map object properties to external APIs, database fields, or other data sources.
Asymmetric Visibility
Asymmetric visibility in PHP 8.4 allows different visibility levels for getters and setters of a property. Previously, the visibility had to be consistent for both getting and setting a property.
How It Works
In previous versions of PHP, if you declared a property as private or protected, both its getter and setter would inherit the same visibility level:
class Example {
private $property;
public function getProperty() {
return $this->property;
}
public function setProperty($value) {
$this->property = $value;
}
}
With asymmetric visibility, you can now do something like this:
class Example {
private $property;
public function getProperty() {
return $this->property;
}
protected function setProperty($value) {
$this->property = $value;
}
}
Future Implications
This change means more granular control over how properties are accessed and modified, leading to better encapsulation and security practices in coding.
New Array Functions
PHP 8.4 introduces several new array functions that bring it closer in functionality to JavaScript's array methods:
- array_find: Finds the first element that matches a given condition.
- array_find_key: Finds the key of the first element that matches a given condition.
- array_any: Checks if any elements match a given condition.
- array_all: Checks if all elements match a given condition.
These functions simplify common array operations and make your code cleaner and more readable.
Chaining on New Classes Without Brackets
One small but impactful change in PHP 8.4 is the ability to chain methods on newly instantiated objects without using brackets:
// Old way
(new ClassName())->method()->anotherMethod();
// New way
new ClassName()->method()->anotherMethod();
This syntactic sugar makes code cleaner and easier to read.
New DateTime Constructors from Timestamps
Creating DateTime objects from timestamps has been made simpler with new constructors:
$datetime = DateTime::createFromTimestamp(time());
This eliminates the need for converting timestamps manually before creating DateTime objects.
PDO Driver Specific Subclasses
PHP 8.4 introduces driver-specific subclasses for PDO, allowing developers to use specialized methods specific to their database driver while still leveraging PDO's abstraction layer.
HTML5 Parse Support
HTML5 parsing support has been improved in PHP 8.4, making it easier to work with modern HTML documents within your applications.
Object API for BCMath
With PHP 8.4, the BCMath API introduces the BcMathNumber
object, enabling object-oriented usage and allowing standard mathematical operators when working with arbitrary precision numbers. These objects are immutable and implement the Stringable
interface, making them suitable for use in string contexts such as echo $num
.
use BcMathNumber;
$num1 = new Number('0.12345');
$num2 = new Number('2');
$result = $num1 + $num2; // Using standard operator
echo $result; // Outputs '2.12345' due to Stringable implementation
var_dump($num1 > $num2); // false
This approach simplifies operations with large numbers by leveraging familiar operators while ensuring immutability and seamless integration into string contexts.
PHP 8.4 Smaller Changes
New Features
- Classes, Interfaces, Functions: New Lazy Objects, updated JIT using IR Framework.
- Math Enhancements:
bcceil()
,bcdivmod()
,bcfloor()
,bcround()
. - Rounding Modes: New
RoundingMode
enum, modes:TowardsZero
,AwayFromZero
,NegativeInfinity
,PositiveInfinity
. - Multibyte Functions:
mb_trim()
,mb_ltrim()
,mb_rtrim()
,mb_ucfirst()
,mb_lcfirst()
. - PCNTL Updates:
pcntl_getcpu()
,pcntl_getcpuaffinity()
,pcntl_getqos_class()
,pcntl_setns()
,pcntl_waitid()
. - Reflection Methods:
ReflectionClassConstant::isDeprecated()
,ReflectionGenerator::isClosed()
,ReflectionProperty::isDynamic()
. - HTTP Functions:
http_get_last_response_headers()
,http_clear_last_response_headers()
. - XMLReader/Writer: Methods like
XMLReader::fromStream()
,XMLWriter::toStream()
. - String Operations:
grapheme_str_split()
for handling graphemes.
Deprecations and BC Breaks
- Extension Changes: IMAP, OCI8, PDO_OCI, PSpell moved to PECL.
- Nullable Parameters: Implicitly nullable types deprecated.
- Deprecated Names:
_
as class name. - Math Changes: Raising 0 to a negative power is deprecated, invalid
round()
modes throwValueError
. - Typed Constants: For
date
,intl
,pdo
, etc. - Removed MYSQLI Constants:
MYSQLI_SET_CHARSET_DIR
,MYSQLI_TYPE_INTERVAL
. - Deprecated MySQLi Methods:
mysqli_ping()
,mysqli_kill()
,mysqli_refresh()
. - Stream Changes:
stream_bucket_make_writeable()
now returnsStreamBucket
. - Miscellaneous:
exit()
behavioural changes,E_STRICT
deprecated.
Conclusion
PHP 8.4 brings numerous enhancements designed to improve developer productivity and code quality. From property hooks offering better encapsulation capabilities to new array functions simplifying common tasks, these updates make PHP an even more powerful language for web development projects. For a comprehensive overview of all the new features, check out the full PHP 8.4 Documentation.
Here at FONSEKA, we are always up to date with the latest technologies to help create the best websites for our clients. By leveraging these advancements in PHP, we ensure that our web development projects are efficient, secure, and cutting-edge.