dtrj21373 2016-06-26 16:53
浏览 14
已采纳

访问对象时的奇怪行为[重复]

This question already has an answer here:

This is my code:

$date1 = new DateTime();
$date1->format('Y-m-d H:i:s');
echo $date1->date. ' while echoing date1';  

It echoes only " while echoing date1", in other words $date1->date is empty.
If I add dump date1 first like this:

$date1 = new DateTime();
$date1->format('Y-m-d H:i:s');
var_dump($date1);
echo $date1->date. ' while echoing date1';  

I get

object(DateTime)[359]
  public 'date' => string '2016-06-26 16:54:56.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

2016-06-26 16:54:56.000000 while echoing date1

which is what I want. This thing is getting me mad as it is completely unexpected.

</div>
  • 写回答

1条回答 默认 最新

  • dongwopu8210 2016-06-26 16:58
    关注

    The format option isn't for setting the format of the object, it's a method that returns the date object as a string in the requested format:

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

    To clarify, what you see as a 'date' within the object is just a text representation for convenience, as internally it will be held in an optimized way. If you want to add it to a string, you need to specify the format you want:

    echo "This is the date ".$date->format('c');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大