In PHP 5.5 the DateTimeImmutable class was introduced. Immutable objects are nice in that they can not be modified, which helps reduce the likelihood I make certain types of errors.
Type Hinting DateTime
When using type declarations (a.k.a. type hinting), you can use the DateTimeInterface
, which accepts either a DateTime
or a DateTimeImmutable
object. This is great but it means I may now have a mutable DateTime
object (instead of a DateTimeImmutable
object).
Convert to DateTimeImmutable
The DateTimeImmutable class comes with a helper static function createFromMutable()
, which takes a DateTime
object and returns a DateTimeImmutable
object. Unfortunately, DateTimeImmutable::createFromMutable()
throws an error if you use a DateTime
object as the parameter, therefore we need to do a check before calling this function.
This is the code I use to ensure my value is an instance of DateTimeImmutable
.
function myFunction(DateTimeInterface $dt) {
$dt = $dt instanceof DateTimeImmutable ?
$dt :
DateTimeImmutable::createFromMutable($dt);
// Now $dt is definitely a DateTimeImmutable object.
// Other code goes here.
}
Leave a Reply