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

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

问题描述

考虑以下代码示例:

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

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

  DateTime对象

[date] => 2013-06-12 15:54: 25
[timezone_type] => 3
[时区] =>欧洲/阿姆斯特丹

2013-06-12 15:54:25

但是以下代码:

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

只是发出错误:



< pre class =lang-none prettyprint-override> 注意:未定义的属性:DateTime :: $ date in ...

为什么 print_r()添加这些属性到对象?请注意,它们未定义为 DateTime 类的一部分。 rel =noreferrer>手册页

解决方案

有一些魔法发生,但很简单。 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.

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

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