Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony: why the backslash in \DateTime(); [duplicate]

Tags:

symfony

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...

like image 995
Snowcrash Avatar asked Dec 05 '22 15:12

Snowcrash


1 Answers

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

like image 175
Stas Parshin Avatar answered Dec 09 '22 03:12

Stas Parshin