[php-src] Issue #8351: explicit `__construct` call for \DateTimeImmutable object would break immutable

From: Date: Thu, 14 Apr 2022 00:25:40 +0000
Subject: [php-src] Issue #8351: explicit `__construct` call for \DateTimeImmutable object would break immutable
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-240943@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/8351 Comment Author: sasezaki Hi, all. The problem with this issue is that a class named Immutable is not immutable using standard PHP functionality. Of course, there is no way to prevent this, since it can be rewritten by extensions such as Reflection. But the barrier to change is high. With PHP 8.1, I thought that an immutable class could be coded as follows Therefore, I was proposing a change to grant readonly. ```php <?php final class OtherDateTimeImmutable { public function __construct( private readonly string $date ) {} } $date = new OtherDateTimeImmutable('now'); $date->__construct('yesterday'); // Fatal error: Uncaught Error: Cannot modify readonly property OtherDateTimeImmutable::$date ```` However, in retrospect, I think this is an encapsulation violation, since the internal structure of the DateTimeImmutable class is known to the user. (As derick comments on https://github.com/php/php-src/issues/8152#issuecomment-1091588907 (It is not intended that each property of DateTimeImmutable be public.) Therefore, as per cmb69's first comment, it would be preferable to throw an exception if it is initialized.

« previous php.bugs (#240943) next »