在 Symfony2 中,\DateTime 是什么意思? [英] In Symfony2, what does \DateTime mean?

查看:20
本文介绍了在 Symfony2 中,\DateTime 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Symfony 2 中,这行是什么意思:

In Symfony 2, what does this line mean:

$task->setDueDate(new \DateTime('tomorrow'));

\DateTime 代表什么?可以从任何地方访问吗?

what does \DateTime signify? Can it be accessed from anywhere?

推荐答案

首先是一个小提示,这与 Symfony 没有任何关系 - 恰好 Symfony2 使用 命名空间.

A small FYI firstly, this doesn't have anything to do with Symfony - it just happens that Symfony2 uses namespaces.

当不使用命名空间时,日期时间类总是通过 new DateTime() 可用 - 这是因为您已经在root"命名空间中.但是,当您使用命名空间时,仅使用 new DateTime() 将不起作用,因为它会在当前命名空间中查找该类.示例:

When not using namespaces, the datetime class is always available through new DateTime() - this is because you're already in the "root" namespace. However, when you're using namespaces, simply using new DateTime() wont work as it will look for that class in the current namespace. Example:

<?php

namespace MyApp\Component;

class Something
{
   function __construct()
   {
      $dt = new DateTime(); 
   }
}

这将导致错误(例如 Class 'MyApp\Component\DateTime' not found in ...),因为 MyApp\Component 中没有类名为 DateTime 的命名空间.

This will cause an error (e.g. Class 'MyApp\Component\DateTime' not found in ...), because there is no class within the MyApp\Component namespace named DateTime.

这就是您找到 \DateTime() 的原因,它告诉解释器查看 DateTime 类的根"(?) 命名空间.

This is why you found \DateTime(), its telling the interpreter to look in the "root" (?) namespace for the class DateTime.

您也可以使用 use 关键字来导入DateTime 类 - 脚本的顶部看起来像 - 这允许您只调用 new DateTime():

You can also use the use keyword to import the DateTime class - the top of your script would look like - this allows you to just call new DateTime():

<?php

namespace MyApp\Component;

use \DateTime;

这篇关于在 Symfony2 中,\DateTime 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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