PHP DateTime 类命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8367811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:32:35  来源:igfitidea点击:

PHP DateTime class Namespace

phpdatetimenamespaces

提问by Miguel Ribeiro

I'm using the symfony2 framework and I want to use the PHP's DateTime class (PHP version is 5.3).

我正在使用 symfony2 框架,我想使用 PHP 的 DateTime 类(PHP 版本为 5.3)。

Here the declaration:

这里的声明:

namespace SDCU\GeneralBundle\Entity;

class Country
{
   public function __construct(){
       $this->insertedAt = new DateTime();
   }
}

But, when executing this constructor, I get an error saying that there's no "SDCU\GeneralBundle\Entity\DateTime" class. I've been searching around for DateTime's namespace but with no success... any idea?

但是,在执行此构造函数时,我收到一条错误消息,指出没有“SDCU\GeneralBundle\Entity\DateTime”类。我一直在寻找 DateTime 的命名空间,但没有成功......知道吗?

回答by str

DateTimeis in the global namespace, and as "class names always resolve to the current namespace name" you have to use \DateTime.

DateTime位于全局命名空间中,并且由于“类名始终解析为当前命名空间名称”,您必须使用\DateTime.

Or import the package using:

或者使用以下命令导入包:

use \Datetime;

回答by Glavi?

Better solution for using classes in global namespaces is "use" keyword instead of "\" before class.

在全局命名空间中使用类的更好解决方案是“use”关键字而不是类之前的“\”。

namespace SDCU\GeneralBundle\Entity;
use \DateTime;

class Country
{
   public function __construct(){
       $this->insertedAt = new DateTime();
   }
}