Created
November 8, 2016 14:47
-
-
Save ManInTheBox/343d9505193e65ce914443315d810990 to your computer and use it in GitHub Desktop.
DateTime VS DateTimeImmutable example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
Awesome
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?
@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
At line you could have used DateTimeInterface as type.