Skip to content

explicit __construct call for \DateTimeImmutable object would break immutable #8351

Closed
@sasezaki

Description

@sasezaki

Description

The following code:

<?php
$date = new \DateTimeImmutable('1970-01-01 00:00:00.000000');
$date->__construct('2000-01-01 00:00:00.000000');

var_dump($date);

Resulted in this output:

object(DateTimeImmutable)#1 (3) {
  ["date"]=>
  string(26) "2000-01-01 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}

https://3v4l.org/hnnIE

But I expected this output instead:

Fatal error: Uncaught Error: Cannot modify readonly property DateTimeImmutable::$date

I did learn this issue when reading this slide.
https://speakerdeck.com/twada/growing-reliable-code-phperkaigi-2022?slide=84

According to the author of this slide, twada, he noticed this problem himself. (after reading https://www.simonholywell.com/post/2017/03/php-and-immutability/ )

I propose to give readonly to each of the properties of \DateTimeImmutable.

PHP Version

PHP 8.1.4

Operating System

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions