print_r() 向 DateTime 对象添加属性 [英] print_r() adds properties to DateTime objects

查看:30
本文介绍了print_r() 向 DateTime 对象添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码示例:

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

自 PHP 5.3 起,这会产生(类似于)以下输出:

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

但是下面的代码:

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

...只是发出一个错误:

...simply emits an error:

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

为什么 print_r() 将这些属性添加"到对象中?请注意,它们未定义为 上的 DateTime 类的一部分手册页.

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.

DateTime 类没有您使用的公共变量日期"意在访问.但是,作为 PHP 工作方式的一个副作用,当您对该类调用 print_r 或 var_dump 时会创建一个变量.

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.

在那魔法发生后,日期"可用,但不应该.您应该只使用 getTimestamp 函数来使您的代码可靠地工作.

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.

这篇关于print_r() 向 DateTime 对象添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆