Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Carbon - variables bound to eachother

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?

Update

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();.

like image 969
Kieran Smith Avatar asked Dec 15 '22 08:12

Kieran Smith


1 Answers

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

like image 92
Gal Avatar answered Dec 22 '22 00:12

Gal