PHP DateTime class Namespace

PhpDatetimeNamespaces

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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;

Solution 2 - Php

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();
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiguel RibeiroView Question on Stackoverflow
Solution 1 - PhpstrView Answer on Stackoverflow
Solution 2 - PhpGlavićView Answer on Stackoverflow