I'm trying to get the current date/time using OOP way as follow:
$now = new \DateTime(); // 2015-05-24 11:21:36 -> this works fine
and also I'm adding 1 week to the same object $now
so I did this:
$expireTime = $now->modify('+1 week'); // 2015-05-31 11:21:36 -> this also works fine
In the same method if I do this:
echo $now;
// Output: 2015-05-31 11:28:59
// Got wrong value, should be original date without modification
echo $expireTime;
// Output: 2015-05-31 11:28:59
// Got the right value since I have added 1 week
Why? How do I add a week without modify the original object?
EDIT: I have found the solution by cloning the original object and modifying the cloned one but I want to know if this behavior is right and why
You are probably looking for the DateTimeImmutable
class, which is the same, but it doesn't change the original value. As from the manual:
This class behaves the same as DateTime except it never modifies itself but returns a new object instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With