1.2.325. DateTimeImmutable Is Not Immutable

DateTimeImmutable is not really immutable because its internal state can be modified after instantiation.

Inspired by the article from Matthias Noback.

<?php

$dt = new DateTimeImmutable('now');
echo $dt->getTimestamp() . "\n";

$dt->__construct('tomorrow');
echo $dt->getTimestamp() . "\n";

?>

See also Effective immutability with PHPStan.

1.2.325.1. Suggestions

  • Remove the call to the constructor after instantation of a DateTimeImmutable object

1.2.325.2. Specs

Short name

Php/DateTimeNotImmutable

Rulesets

All, Analyze

Exakat since

2.4.5

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Available in

Entreprise Edition, Exakat Cloud