Skip to content

Instantly share code, notes, and snippets.

@ManInTheBox
Created November 8, 2016 14:47
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ManInTheBox/343d9505193e65ce914443315d810990 to your computer and use it in GitHub Desktop.
Save ManInTheBox/343d9505193e65ce914443315d810990 to your computer and use it in GitHub Desktop.
DateTime VS DateTimeImmutable example
<?php
class DateTimeImmutabilityExample
{
private $date;
/**
* Intentionaly no type hinting so you can test with both DateTime and DateTimeImmutable
*/
public function __construct($date)
{
$this->date = $date;
}
public function dump()
{
var_dump($this->date->format('Y-m-d'));
}
}
$today = new DateTime();
$bad = new DateTimeImmutabilityExample($today);
$bad->dump(); // string(10) "2016-11-08"
// Modify internal state of DateTimeImmutabilityExample instance
$today->add(DateInterval::createFromDateString('10 days'));
$bad->dump(); // string(10) "2016-11-18" <-- this is BAD!
$today = new DateTimeImmutable();
$good = new DateTimeImmutabilityExample($today);
$good->dump(); // string(10) "2016-11-08"
$today->add(DateInterval::createFromDateString('10 days'));
$good->dump(); // string(10) "2016-11-08" <-- original $date is not changed
@ioanszabo
Copy link

At line you could have used DateTimeInterface as type.

public function __construct(DateTimeInterface  $date)
    {
        $this->date = $date;
    }

@stevemosiori
Copy link

Awesome

@agungsugiarto
Copy link

Can anyone tell me, i don't get it. So when we use DateTimeImmutable() instead of using DateTime() i mean in real case or scenario?

@bluemanos
Copy link

@agungsugiarto here https://www.nikolaposa.in.rs/blog/2019/07/01/stop-using-datetime/ the autor quite good explained the problem.

But related to above example. As you see, you was able to change a Date from outside of DateTimeImmutabilityExample class. Thats extreme dangerous!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment