1.2.1334. Use DateTimeImmutable Class¶
The DateTimeImmutable
class is the immutable version of the Datetime
class.
While DateTime
may be modified, DateTimeImmutable
cannot be modified : it needs to be cloned instead. Any modification to such an object will return a new and distinct object. This prevents alterations that are hard to track.
<?php
// Example extracted from Derick Rethans' article (link below)
function formatNextMondayFromNow( DateTime $dt )
{
return $dt->modify( 'next monday' )->format( 'Y-m-d' );
}
$d = new DateTime(); //2014-02-17
echo formatNextMondayFromNow( $d ), "\n";
echo $d->format( 'Y-m-d' ), "\n"; //2014-02-17
?>
See also What’s all this ‘immutable date’ stuff, anyway?, DateTimeImmutable, The DateTime class and The DateTimeImmutable class.
1.2.1334.1. Connex PHP features¶
1.2.1334.1.1. Suggestions¶
Always use DateTimeImmutable when manipulating dates.
1.2.1334.1.2. Specs¶
Short name |
Php/UseDateTimeImmutable |
Rulesets |
|
Exakat since |
1.8.7 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |