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 of copy

Check out the documentation: https://carbon.nesbot.com/docs/

Leave a Comment

error code: 521