Php 为什么我的变量是通过引用传递的?
我创建了一个函数,该函数在第一个日期时间的基础上创建了两个日期时间:Php 为什么我的变量是通过引用传递的?,php,function,variables,datetime,reference,Php,Function,Variables,Datetime,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
// 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通过引用传递所有对象
这里有更多信息:正如其他人所注意到的,PHP中的所有对象都被传递 如果要更改对象以保持原始对象的完整性,应使用 对象(基本上)通过引用传递。请参见此处了解更多详细信息:从oop参考“经常提到的PHP5OOP的关键点之一是“默认情况下对象是通过引用传递的”。这并不完全正确
$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