New in PHP 8
#Weak maps RFC
Built upon the weakrefs RFC that was added in PHP 7.4, a WeakMap
implementation is added in PHP 8. WeakMaps
hold references to objects, which don’t prevent those objects from being garbage collected.
Take the example of ORMs, they often implement caches which hold references to entity classes to improve the performance of relations between entities. These entity objects can not be garbage collected, as long as this cache has a reference to them, even if the cache is the only thing referencing them.
If this caching layer uses weak references and maps instead, PHP will garbage collect these objects when nothing else references them anymore. Especially in the case of ORMs, which can manage several hundreds, if not thousands of entities within a request; weak maps can offer a better, more resource friendly way of dealing with these objects.
Here’s what weak maps look like, an example from the RFC:
class Foo
{
private WeakMap $cache;
public function getSomethingWithCaching(object $obj): object
{
return $this->cache[$obj]
??= $this->computeSomethingExpensive($obj);
}
}
#::class
on objects RFC
A small, yet useful, new feature: it’s now possible to use ::class
on objects, instead of having to use get_class()
on them. It works the same way as get_class()
.
$foo = new Foo();
var_dump($foo::class);
#Create DateTime objects from interface
You can already create a DateTime
object from a DateTimeImmutable
object using DateTime::createFromImmutable($immutableDateTime)
, but the other way around was tricky. By adding DateTime::createFromInterface()
and DatetimeImmutable::createFromInterface()
there’s now a generalised way to convert DateTime
and DateTimeImmutable
objects to each other.
DateTime::createFromInterface(DateTimeInterface $other);
DateTimeImmutable::createFromInterface(DateTimeInterface $other);