且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

print_r()将属性添加到DateTime对象

更新时间:2023-12-01 21:40:46

有一些魔法发生,但很简单。 p>

DateTime 没有您要访问的公共变量'date'。但是,作为PHP工作原理的一个副作用,当您在该类中调用print_r或var_dump时,会创建一个变量。



发生魔术之后,date可用,但不应该。您应该使用getTimestamp函数使您的代码可靠地工作。


Consider the following code sample:

$m_oDate = new DateTime('2013-06-12 15:54:25');
print_r($m_oDate);
echo $m_oDate->date;

Since PHP 5.3, this produces (something like) the following output:

DateTime Object
(
    [date] => 2013-06-12 15:54:25
    [timezone_type] => 3
    [timezone] => Europe/Amsterdam
)
2013-06-12 15:54:25

However the following code:

$m_oDate = new DateTime('2013-06-12 15:54:25');
echo $m_oDate->date;

...simply emits an error:

Notice: Undefined property: DateTime::$date in ...

Why does print_r() "add" these properties to the object? Note that they are not defined as part of the DateTime class on the manual page.

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.