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


Why are my variables passed by reference?

我创建了一个函数,该函数基于第一个创建了两个日期时间:

// 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

目前,一切都很好。现在,我将这些日期时间传递到另一个函数中,在该函数中,我使用while循环来递增第一个日期,直到她到达第二个日期:

// 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

我的函数generateDateKeys中的while循环似乎没有在本地修改参数。它在函数外更改$dates的值。但我从不使用引用传递。

有人能告诉我这件事吗?

PHP默认情况下通过引用传递所有对象。

更多信息请点击此处:http://php.net/manual/en/language.oop5.references.php

正如其他人所注意到的,PHP中的所有对象都是通过引用传递的。

如果要更改对象以保持原始对象不变,则应使用clone关键字。

$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