The readonly properties were introduced in PHP 8.1. These properties can only be set once and cannot be changed afterward. If class is declared as readonly, when all class properties automatically become readonly.
Before PHP 8.3, cloning readonly properties was not possible, posing a significant limitation and preventing to implement more advanced scenarios. Since PHP 8.3, it is possibility to reinitialize readonly properties during cloning.
Let's say we have readonly class that defines the __clone
magic method, in which a new DateTime
object is created by cloning the existing createdAt
property.
<?php
readonly class Episode
{
public function __construct(private DateTime $createdAt)
{
}
public function getCreatedAt(): DateTime
{
return $this->createdAt;
}
public function __clone(): void
{
$this->createdAt = clone $this->createdAt;
}
}
Before PHP 8.3, attempting to clone this object would result in a fatal error.
<?php
require_once 'Episode.php';
$instance = new Episode(new DateTime('2023-12-03'));
$cloned = clone $instance;
PHP Fatal error: Uncaught Error: Cannot modify readonly property Episode::$createdAt in Episode.php:16
Since PHP 8.3, this limitation has been removed and now possible to reinitialize readonly properties during cloning.
<?php
require_once 'Episode.php';
$instance = new Episode(new DateTime('2023-12-03'));
// All good
$cloned = clone $instance;
$cloned->getCreatedAt()->setDate(2023, 12, 4);
Leave a Comment
Cancel reply