I’m trying to modify a DateTime object in a function passed as an reference:
<?php
$date = new DateTime('2012-02-12');
for($n1 = 0; $n1 < 10; $n1++) {
$date->modify('first day of next month');
setDate($date, 15);
echo $date->format('Y-m-d') . "<br />\n";
}
function setDate(&$date, $day) {
$date->setDate($date->format('Y'), $date->format('m'), $day);
}
?>
But the result is not as expected. Did I got something wrong with this references stuff?
EDIT:
Expected result:
2012-03-15
2012-04-15
…
Result with function above:
2012-03-01
2012-04-01
…
My PHP didn’t like the ‘first day of nest month’ bit, but worked with ‘+1 month’. Since you are setting the day absolutely I wouldn’t worry about it not being on the first. Or if it needs to be you can set it to the first before you go into the loop.
So, this worked for me. I added the
new DateTimeZone('America/New_York')so it would stop bugging me about it not being set (shared server.) And removed the pass by reference (&) bit since all objects are passed by reference by default in PHP now.