【问题标题】:PHP DateTime class NamespacePHP DateTime 类命名空间
【发布时间】:2012-01-12 03:50:44
【问题描述】:

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

声明如下:

namespace SDCU\GeneralBundle\Entity;

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

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

【问题讨论】:

    标签: php datetime namespaces


    【解决方案1】:

    DateTime 在全局命名空间中,作为“class names always resolve to the current namespace name”你必须使用\DateTime

    或使用以下方式导入包:

    use \Datetime;
    

    【讨论】:

    • 你也可以把use \Datetime;放在命名空间和类声明之间,继续使用DateTime。另一点:这也适用于Exception!捕捉 Exception 你应该捕捉 \Exception 不会给出错误,你只是没有捕捉到任何东西!
    【解决方案2】:

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

    namespace SDCU\GeneralBundle\Entity;
    use \DateTime;
    
    class Country
    {
       public function __construct(){
           $this->insertedAt = new DateTime();
       }
    }
    

    【讨论】:

    • 应该是use \DateTime,而不是use DateTime
    • 如果你在本地命名空间中有一个与全局命名空间同名的类,你必须在`\`前加上前缀,否则你将导入本地类。
    • 我喜欢这个,在某种程度上让我想起了其他语言,比如 Python,当你需要使用一个作为核心的一部分的类时,你可以使用看起来很干净的 use 将其引入 IMO跨度>
    猜你喜欢
    • 2014-08-12
    • 2016-03-25
    • 2012-08-10
    • 2011-09-04
    • 2012-08-10
    • 2010-11-27
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多