PHP Carbon class changing my original variable value
When you run these methods against a Carbon object it updates the object itself. Therefore addDay()
moves the value of Carbon one day forward.
Here's what you need to do:
$now = Carbon::now();$now->copy()->addDay();$now->copy()->addMonth();$now->copy()->addYear();// etc...
The copy method essentially creates a new Carbon object which you can then apply the changes to without affecting the original $now
variable.
To sum up, the methods for copying a Carbon instance are:
copy
clone
- an alias ofcopy
Check out the documentation: https://carbon.nesbot.com/docs/
The problem is that you're assuming that subDay()/addDay() don't change the date object, whereas they do.... they're just wrapping around the DateTime
object modify()
method:
DateTime::modify -- date_modify — Alters the timestamp
(my emphasis)
Instead, use
$navDays = [ '-7Days' => (clone $date)->subDay('7')->toDateString(), '-1Day' => (clone $date)->subDay('1')->toDateString(), 'Today' => (clone $date)->today()->toDateString(), '+1Day' => (clone $date)->addDay('1')->toDateString(), '+7Days' => (clone $date)->addDay('7')->toDateString()];
Doco says
You can also create a copy() of an existing Carbon instance. As expected the date, time and timezone values are all copied to the new instance.
$dt = Carbon::now();echo $dt->diffInYears($dt->copy()->addYear()); // 1// $dt was unchanged and still holds the value of Carbon:now()