为什么我不能在 PHP 的 DateTime 类中访问 DateTime->date? [英] Why can't I access DateTime->date in PHP's DateTime class?

查看:25
本文介绍了为什么我不能在 PHP 的 DateTime 类中访问 DateTime->date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 DateTime 类,如果我尝试运行以下代码:

Using the DateTime class, if I try to run the following code:

$mydate = new DateTime();
echo $mydate->date;

我会回复这个错误信息

注意:未定义的属性:DateTime::$date...

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

这没有意义,因为当在变量 $mydate 上运行 var_dump() 时,它清楚地表明该属性存在并且可以公开访问:

Which doesn't make sense because when running var_dump() on the variable $mydate, it clearly shows that this property exists and is publicly accessible:

var_dump($mydate);

object(DateTime)[1]
  public 'date' => string '2012-12-29 17:19:25' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

这是 PHP 中的错误还是我做错了什么?我使用的是 PHP 5.4.3.

Is this a bug within PHP or am I doing something wrong? I'm using PHP 5.4.3.

推荐答案

这是一个已知问题.

可用日期实际上是支持 var_dump() 的副作用——derick@php.net

Date being available is actually a side-effect of support for var_dump() here – derick@php.net

出于某种原因,您不应该能够访问该属性,但 var_dump 无论如何都会显示它.如果您真的想以该格式获取日期,请使用 DateTime::format() 函数.

For some reason, you're not supposed to be able to access the property but var_dump shows it anyways. If you really want to get the date in that format, use the DateTime::format() function.

echo $mydate->format('Y-m-d H:i:s');

这篇关于为什么我不能在 PHP 的 DateTime 类中访问 DateTime->date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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