4

Why does this line of Symfony code have a backslash before DateTime()?

$this->updated_datetime = new \DateTime();

I'm pretty sure this has something to do with NameSpaces but can someone confirm / clarify...

Snowcrash
  • 80,579
  • 89
  • 266
  • 376

1 Answers1

16

Because it makes php to refer to the root (global) namespace that way.

You could also use DateTime first and then go without a slash:

namespace MyCompany\MyBundle\MyController;

use \DateTime;

$d = new DateTime();

Say you are working on your controller which sits under MyCompany\MyBundle\MyController namespace. So what happens when you try to create a new DateTime instance?

Autoloader attempts to find it under the same namespace i.e. it looks for a class with fully qualified name MyCompany\MyBundle\MyController\DateTime. As a result - you are getting an "Attempted to load class from namespace ... " exception.

That's why you need to add a slash - it makes php to look for the class under the global namespace rather than the local one.

Check out this page: http://php.net/manual/en/language.namespaces.global.php

Stas Parshin
  • 1,458
  • 1
  • 16
  • 21