Symfony: why the backslash in \DateTime();

This question already has an answer here:

  • What does a (backslash) do in PHP (5.3+)? 3 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 MyCompanyMyBundleMyController;
    
    use DateTime;
    
    $d = new DateTime();
    

    Say you are working on your controller which sits under MyCompanyMyBundleMyController namespace. So what happens when you try to create a new DateTime instance?

    Autoloader attempts to find it under the same namespace ie it looks for a class with fully qualified name MyCompanyMyBundleMyControllerDateTime . 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

    链接地址: http://www.djcxy.com/p/58130.html

    上一篇: 这个PHP代码中的反斜杠是做什么的?

    下一篇: Symfony:为什么\ DateTime()中的反斜杠;