2013-12-18 31 views
0

我不知道這是否是專門Symfony2.4.0相關的,但是當我有一個Symfony2.4.0新反斜槓類名()

<?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 
    } 
} 

此代碼的工作好了,但到底是什麼反斜槓在DateTime()的前面是什麼意思?只要我刪除反向斜槓我得到這個錯誤:

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

是否反向斜線某種逃避回到根命名空間?我可以有這個代碼

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

它可以在DateTime()之前有或沒有反斜槓正常工作。

+0

[Backslash in PHP中的可能的重複 - 這是什麼意思?](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 –

+0

我原本有這個問題張貼作爲轉發斜槓,所以谷歌搜索答案沒有結果。多謝你們。 –

回答

1

命名空間可以讓你與內置類相同的名稱作爲PHP的定義自己的類,所以你可以有(全部在一個文件中): -

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

因此,\告訴PHP使用根名稱空間而不是你的名字。你確實有時候不需要它,但這是一個好習慣,以避免以後很難跟蹤錯誤上。

+0

如果爲根DateTime類添加使用語句,則可以在不使用/的情況下對其進行實例化。 – catchamonkey

+1

@catchamonkey是的,這是真的,但問題是關於使用'\\'。 – vascowhite

1

如果在文件的開頭使用名稱空間,則調用new DateTime()將在同一名稱空間中查找名稱爲DateTime的類,這將返回錯誤。通過new \DateTime(),PHP將在其基類中搜索此類。

你的最後一個例子的作品,因爲它沒有使用命名空間,沒有找到DateTime類的歧義。