Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Symfony2, what does \DateTime mean?

Tags:

php

symfony

In Symfony 2, what does this line mean:

$task->setDueDate(new \DateTime('tomorrow'));

what does \DateTime signify? Can it be accessed from anywhere?

like image 968
Hrishikesh Choudhari Avatar asked Mar 13 '13 16:03

Hrishikesh Choudhari


1 Answers

A small FYI firstly, this doesn't have anything to do with Symfony - it just happens that Symfony2 uses namespaces.

When not using namespaces, the datetime class is always available through new DateTime() - this is because you're already in the "root" namespace. However, when you're using namespaces, simply using new DateTime() wont work as it will look for that class in the current namespace. Example:

<?php

namespace MyApp\Component;

class Something
{
   function __construct()
   {
      $dt = new DateTime(); 
   }
}

This will cause an error (e.g. Class 'MyApp\Component\DateTime' not found in ...), because there is no class within the MyApp\Component namespace named DateTime.

This is why you found \DateTime(), its telling the interpreter to look in the "root" (?) namespace for the class DateTime.

You can also use the use keyword to import the DateTime class - the top of your script would look like - this allows you to just call new DateTime():

<?php

namespace MyApp\Component;

use \DateTime;
like image 65
Prisoner Avatar answered Oct 04 '22 00:10

Prisoner