PHP DateTime类命名空间

57
我使用Symfony2框架,并希望使用PHP的DateTime类(PHP版本为5.3)。
这是声明:
namespace SDCU\GeneralBundle\Entity;

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

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

2个回答

102

14
在命名空间和类声明之间加入use \Datetime;,就可以继续使用DateTime。另外一个要点是:这也适用于Exception!在你应该捕获\Exception的地方捕获Exception不会出错,但你什么也没捕获到! - Nanne

23
使用全局命名空间中的类的更好解决方案是使用 "use" 关键字,而不是在类之前使用 "\"。
namespace SDCU\GeneralBundle\Entity;
use \DateTime;

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

1
应该使用use \DateTime,而不是use DateTime - Alessandro Desantis
4
如果你在本地命名空间中有一个与全局命名空间中同名的类,你必须使用 \\ 前缀,否则你只会导入本地的那个类。注意不要改变原意。 - Problematic
我喜欢这个,它让我想起了其他语言,比如 Python,在某种程度上,当你需要使用核心的类时,你可以通过 use 将其引入,这看起来很干净。 - JasonDavis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接