I have created different vars using date_format
from one datetime
object $date_obj
.
$date_obj = date_create($date);
$year = date_format($date_obj, 'Y');
$month = date_format($date_obj, 'm');
$day = date_format($date_obj, 'd');
However I have read (lost source) that this is bad practice? Instead I should create a new datetime
object each time because the original object isn't referenced, but directly manipulated.
$date_obj_1 = date_create($date);
$year = date_format($date_obj_1, 'Y');
$date_obj_2 = date_create($date);
$month = date_format($date_obj_2, 'm');
$date_obj_3 = date_create($date);
$day = date_format($date_obj_3, 'd');
Is this true?
The DateTime object is an object, and therefore is passed by reference.
In your example above this won't matter, because you only format a date, you do not manipulate it. However, if you use a DateTime object as an argument in a function and inside this function you manipulate the object, your changes will be visible outside of that function:
function addDays($date,$days){
$date->add(new DateInterval($days.' days'));
}
$date_obj_1 = date_create($date);
$formatedDate1 = date_format($date_obj_1, 'Y-m-d');
addDays($date_obj_1,10);
$formatedDate2 = date_format($date_obj_1, 'Y-m-d');
In the above example $formatedDate1 is different from $formatedDate1 because $date_obj_1 was passed by reference
EDIT: for a detailed explanation on my above snipped look at the comments section. @Xatoo explained it pretty good.
date_format
isn't manipulating the DateTime object. What you do is the equivalent of:
$dateObject = new DateTime($date);
$year = $dateObject->format('Y');
$month = $dateObject->format('m');
$day = $dateObject->format('d');
This is absolutely fine, dateObject
is not changed by calling the format method on it.