In Symfony 2, what does this line mean:
$task->setDueDate(new \DateTime('tomorrow'));
what does \DateTime
signify? Can it be accessed from anywhere?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With