为什么我的变量通过引用传递?

I created a function that created two datetimes based on a first one :

// initial datetime (for test)
$dt = new \Datetime;
$dt->setDate(2012, 9, 5);

// splitting into 2 different datetimes
$dates = $this->defineLimitsByDate($dt);

// $dates[0] = 2011-07-01
// $dates[1] = 2012-09-01

For the moment, everything's right. Now I pass these datetimes into an other function in which I use a while loop that increments the first date until she reaches the second one :

// now I use the 2 datetimes into a function...
$dateKeys = $this->generateDateKeys($dates[0], $dates[1]);

// and the function seems to modify them outside itself !
// $dates[0] = 2012-10-01
// $dates[1] = 2012-09-01

It seems that the while loop inside my function generateDateKeys is not locally modifying the parameters. It changes the value of $dates outside the function. But I never use a reference passing.

Can anyone enlighten me about it ?

PHP passes all object by reference, by default.

More informations here : http://php.net/manual/en/language.oop5.references.php

As others have noticed, all objects in PHP are passed by reference.

If you want to alter an object keeping the original intact, you should use the clone keyword.

$originalDate = new \DateTime;
$originalDate->setDate(2010,1,1);

$newDate = clone $originalDate;
$newDate->addYears(1); // pseudo function

// first date is still 2010.01.01, second is 2011.01.01