This article is part of the CakeDC Advent Calendar 2024 (December 16th 2024)
In this article, we will continue to explore the new features and improvements added in the latest version of PHP 8.4.
This is the third article in this series, we encourage you to read the first and second article from the series.
In this release, we have received several long-awaited improvements, improved functionality, and a modern approach to common tasks. These few seem to be the most interesting:
- Lazy Objects
- Object API for BCMath
Lazy Objects
Lazy objects are objects that are initialized when the state of the object is observed or modified.
The use of this type of objects can take place in several scenarios:
-
Let's assume that you have an object that is expensive to create and may not always be used. For example, when you have an Invoice object that has a LineItems property containing a large amount of data retrieved from the database. If the user asks to display a list of invoices without their content, Lazy Object functionality will prevent unnecessary waste of resources.
-
Let's assume that you have an object that is expensive to create and you would like to delay its initialization until other expensive operations are performed. For example, you are preparing user data for export, but using Lazy Objects you can delay loading data from the database and perform, for example, authentication to an external API and preparation tasks, and only during export the data from the database will be loaded.
Lazy objects can be created in two strategies:
- Ghost Objects - such lazy objects are indistinguishable from normal objects and can be used without knowing that they are lazy.
- Virtual Proxies - in this case, the lazy object and the real instance are separate identities, so additional tasks must be performed when accessing the Virtual Proxy.
Creating Ghost Objects
Lazy ghost strategy should be used when we have control over the instatiation and initialization of an object. Lazy ghost is indistinguishable from a real instance of the object.
class LazyGhostExample
{
public function __construct(public string $property)
{
echo "LazyGhost initialized\n";
}
}
$reflectionClass = new \ReflectionClass(LazyGhostExample::class);
$newLazyGhost = $reflectionClass->newLazyGhost(function (LazyGhostExample $lazyGhostExample) {
$lazyGhostExample->__construct('example');
});
// the object is not initialized yet
var_dump($newLazyGhost);
// the object is of class LazyGhostExample
var_dump(get_class($newLazyGhost));
// the object is initialized on the first observation (reading the property)
var_dump($newLazyGhost->property);
The above example will output:
lazy ghost object(LazyGhostExample)#15 (0) {
["property"]=>
uninitialized(string)
}
string(28) "LazyGhostExample"
LazyGhost initialized
string(7) "example"
Creating Virtual Proxies
Lazy proxies after initialization are intermediaries to the real object instance, each operation on the proxy is redirected to the real object. This approach is good when we do not control the object initialization process. In the example below, we see that we are returning a new instance of the object, thus we do not interfere with what is happening in the constructor.
class LazyProxyExample
{
public function __construct(public string $property)
{
echo "LazyGhost initialized\n";
}
}
$reflectionClass = new \ReflectionClass(LazyProxyExample::class);
$newLazyProxy = $reflectionClass->newLazyProxy(
function (LazyProxyExample $lazyProxyExample): LazyProxyExample {
return new LazyProxyExample('example');
}
);
// the object is not initialized yet
var_dump($newLazyProxy);
// the object is of class LazyGhostExample
var_dump(get_class($newLazyProxy));
// the object is initialized on the first observation (reading the property)
var_dump($newLazyProxy->property);
The above example will output:
lazy proxy objectLazyProxyExample)#15 (0) {
["property"]=>
uninitialized(string)
}
string(28) "LazyProxyExample"
LazyGhost initialized
string(7) "example"
What triggers the initialization of Lazy Objects
Lazy Objects are initialized when one of the following operations occurs:
- reading or writing a property
- testing whether a property is set or unsetting it
- reading, changing, or listing a property using the
ReflectionProperty
andReflectionObject
classes - serializing an object or cloning it
- iterating through an object using
foreach
if the object does not implementIterator
orIteratorAggregate
Object API for BCMath
Another new feature is an object oriented way of performing mathematical operations on numbers with arbitrary
precision numbers. The new class BcMatch\Number
is used for this purpose. Below is an example of how to use
objects of this class for mathematical operations.
$pi = new BcMath\Number('3.14159');
$euler = new BcMath\Number('2.71828');
// we can just sum both instances
$sum1 = $pi + $euler;
var_dump($sum1);
// we can use chaining to do the same
$sum2 = $pi->add($euler);
var_dump($sum2);
// we can compare the objects
var_dump($pi > $euler);
// we also can compare using method chaining, it this case we will get results
// -1 if argument of compare is greater that the number instance
// 0 if the argument of compare is equal to number instance
// 1 if the argument of compare is greater than number instance
var_dump($euler->compare($pi));
This new class is not yet documented in the php documentatjo so is the complete list
of methods that can be found in the BcMath\Number
class:
namespace BcMath {
/**
* @since 8.4
*/
final readonly class Number implements \Stringable
{
public readonly string $value;
public readonly int $scale;
public function __construct(string|int $num) {}
public function add(Number|string|int $num, ?int $scale = null): Number {}
public function sub(Number|string|int $num, ?int $scale = null): Number {}
public function mul(Number|string|int $num, ?int $scale = null): Number {}
public function div(Number|string|int $num, ?int $scale = null): Number {}
public function mod(Number|string|int $num, ?int $scale = null): Number {}
/** @return Number[] */
public function divmod(Number|string|int $num, ?int $scale = null): array {}
public function powmod(Number|string|int $exponent, Number|string|int $modulus, ?int $scale = null): Number {}
public function pow(Number|string|int $exponent, ?int $scale = null): Number {}
public function sqrt(?int $scale = null): Number {}
public function floor(): Number {}
public function ceil(): Number {}
public function round(int $precision = 0, \RoundingMode $mode = \RoundingMode::HalfAwayFromZero): Number {}
public function compare(Number|string|int $num, ?int $scale = null): int {}
public function __toString(): string {}
public function __serialize(): array {}
public function __unserialize(array $data): void {}
}
}
Conclusion
The above features greatly extend the capabilities of the PHP language.
In addition to these improvements, PHP 8.4 also offers a number of other minor improvements and additions, check the detailed changelog for more information
This article is part of the CakeDC Advent Calendar 2024 (December 16th 2024)