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.
<?php
$date = new DateTime('2012-02-12',new DateTimeZone('America/New_York'));
for($n1 = 0; $n1 < 10; $n1++) {
$date->modify('+1 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);
}
?>
You are already passing a reference to the DateTime object. There is no need to pass an instance of DateTime implicitly as a reference. If you need a copy of the DateTime object, you will need to use clone keyword.
As far as the result, it iterates over 15th of every sequential month, which, reading the code, I expected to be the outcome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With