When using PHP Carbon in a Laravel 5.2 controller, variables appear to be binding to each other. So a change to one affects the others;
PHP Function:
$now = Carbon::now();
var_dump($now);
$from = $now;
$from->startOfYear();
var_dump('-----------------------------------');
var_dump($now, $from);
Results in:
object(Carbon\Carbon)[225]
public 'date' => string '2016-02-13 21:55:36.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
string '-----------------------------------' (length=35)
object(Carbon\Carbon)[225]
public 'date' => string '2016-01-01 00:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
object(Carbon\Carbon)[225]
public 'date' => string '2016-01-01 00:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
Setting $from
to the start of the year has also affected $now
and I cannot see why, and searching the internet gives me nothing. Further in the function I will need to access and manipulate Carbon dates based off other Carbon dates, so I cannot use Carbon::now()
for every separate instance of a Carbon date.
How can I solve this issue? And what is causing it?
I can't answer why it's happening but I've found a temporary solution until I can get to the bottom of it. Create a new Carbon date from the original Carbon date, turned to a string. For example, $from = $new;
becomes $from = new Carbon($now->toDateTimeString());
. You can access methods as usual too;
$from = (new Carbon($now->toDateTimeString()))->startOfYear();
.
when you assign an object you assign its memory address so basically instead of creating 2 different carbon objects you have made 2 references to the same object.
instead of this -
$from = $now;
use -
$from = clone $now;
you can also use carbon copy()
method which basically does the same thing as you did in your 'hack' -
$from = $now->copy();
PHP Object Cloning
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