Print_R() Adds Properties to Datetime Objects

print_r() adds properties to DateTime objects

There is some magic occurring but it's pretty simple.

The class DateTime doesn't have a public variable 'date' that you're meant to access. However, as a side effect of how PHP works, there is a variable created when you call print_r or var_dump on that class.

After that magic happens 'date' is available, but it shouldn't be. You should just use the getTimestamp function to make your code work reliably.

DateTime instance property changes due to a var_dump() or print_r()

timezone is not a property of a new DateTime class. You can verify that by trying to access it immediately after creating the DateTime object.

$date = new DateTime;
echo $date->timezone;

This will get you an undefined property notice.

PHP creates the timezone property to display when you do print_r or var_dump on the object, but modifying that property does not modify the underlying data.

The next time you var_dump or print_r the object, the display properties will be regenerated, overwriting your changes.

You can use the setTimezone method instead if you really do need to change the timezone.

$date->setTimezone(new DateTimeZone('Europe/Madrid'));

(Or set the timezone in your PHP configuration.)


Interestingly enough, referring directly to the timezone property still shows the old value even after you update it with setTimezone. Apparently you need to var_dump the whole object for it to recreate those properties.

$date = new DateTime;
var_dump($date); // Shows 'UTC'
$date->setTimezone(new DateTimeZone('Europe/Madrid'));
var_dump($date->timezone); // Still shows 'UTC' (!)
var_dump($date); // Shows 'Europe/Madrid'
var_dump($date->timezone); // Shows 'Europe/Madrid'

Echo is not printing the object value

The DateTime class does not have a property called date.

You are probably looking for DateTime::format(string) to output a date with a specific format.

For example:

echo $dateTime->format('Y-m-d H:i')
// prints: 2014-05-13 12:29

How to get key's value from object?


<?php
$now = new DateTime(NULL);

echo $now->format("Y-m-d h:i:s");

see http://php.net/manual/en/datetime.format.php

also see related: Why can't I access DateTime->date in PHP's DateTime class? Is it a bug? and print_r() adds properties to DateTime objects



Related Topics



Leave a reply



Submit