Philip Philip - 22 days ago 6
PHP Question

PHP object is being stored in variable as a reference rather than value

I have an object that stores the current date using Carbon as such:



class Events {

public $monthRange = 12;

public $today;

public function __construct() {
$this->today = Carbon::now();
}
}


I have a class that extends that class where I want to set a variable of $d = $this-today as such:



namespace Events;

use Carbon\Carbon;

class EventsData extends Events {

public $monthsNames = [
"1" => "January",
"2" => "February",
"3" => "March",
"4" => "April",
"5" => "May",
"6" => "June",
"7" => "July",
"8" => "August",
"9" => "September",
"10" => "October",
"11" => "November",
"12" => "December"
];
public function next_12_months() {
$next_12_months = [];
$d = $this->today;

array_push($next_12_months, $d->month);
for ( $i = 0; $i <= ($this->monthRange - 1); $i++ ) {
$d = $d->addMonths(1);
if ( $this->today != $d) {
array_push($next_12_months, $d->year);
}
var_dump($$this->today); //is being modified along with $d
var_dump($d);
$next_month = $d->month;
array_push($next_12_months, $next_month);
}

return $next_12_months;
}
}


The problem is that when i modified $d like this $d->addMonths(1), it seems $this->today also gets modified.

How do I prevent this from happening?

qkr qkr
Answer

Clone the object

$d = clone $this->today;

More about cloning here.

Comments