PHP 日期时间类命名空间

2022-08-30 10:15:17

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

这里声明如下:

namespace SDCU\GeneralBundle\Entity;

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

但是,在执行此构造函数时,我收到一个错误,指出没有“SDCU\GeneralBundle\Entity\DateTime”类。我一直在搜索DateTime的命名空间,但没有成功...任何想法?


答案 1

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

或者使用以下方法导入包:

use \Datetime;

答案 2

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

namespace SDCU\GeneralBundle\Entity;
use \DateTime;

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

推荐