0

I'm not sure if this is specifically Symfony2.4.0 related, but when I have a

<?php
namespace Wow\DogeBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ProbeCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this ->setName('a:name')
             ->setDescription('wow');
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {    
        $whenithappened = new \DateTime();
        //more code
    }
}

This code works alright, but what does the backward slash in front of DateTime() mean? As soon as I remove the backward slash I get this error:

PHP Fatal error:  Class 'Wow\DogeBundle\Command\DateTime'

Is the backward slash some sort of escape to go back to the root namespace? I can have this code

<?php
$whenithappened = new \DateTime();
var_dump($whenithappened);
?>

which works fine with or without the backward slash in front of DateTime().

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
No_name
  • 2,732
  • 3
  • 32
  • 48
  • possible duplicate of [Backslash in PHP -- what does it mean?](http://stackoverflow.com/questions/10788400/backslash-in-php-what-does-it-mean), http://stackoverflow.com/questions/4790020/what-does-backslash-do-php5-3, http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – Mike B Dec 18 '13 at 15:37
  • I originally had this question posted as forwards slash, so googling for an answer yielded no results. Thanks guys. – No_name Dec 18 '13 at 15:42

2 Answers2

1

If you use a namespace in the beginning of the file, calling new DateTime() will look for a class with name DateTime in the same namepace, this will return an error. With new \DateTime(), PHP will search for this classes in its base classes.

Your last exemple works because it uses no namespace, there is no ambiguity for finding the DateTime class.

A.L
  • 10,259
  • 10
  • 67
  • 98
1

Namespacing allows you to define your own classes with the same names as PHP's built in classes, so you could have (all in one file):-

namespace my\name

class DateTime
{
    //some code here
}

$myDateTime = new DateTime(); // <- uses your DateTime class
$dateTime = new \DateTime();  // <- uses PHP's built in DateTime class.

see it working.

So the \ is telling PHP to use the root namespace rather than yours.You are correct that there are times when you don't need it, but it is a good habit to get into to avoid hard to track bugs later on.

vascowhite
  • 18,120
  • 9
  • 61
  • 77