Home » Php » PHP DateTime class Namespace

PHP DateTime class Namespace

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m using the symfony2 framework and I want to use the PHP’s DateTime class (PHP version is 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?

How to&Answers:

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

Or import the package using:

use \Datetime;

Answer:

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

namespace SDCU\GeneralBundle\Entity;
use \DateTime;

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