dtwncxs3547 2018-03-24 00:13
浏览 29
已采纳

了解嵌套的命名空间及其范围

  1. Suppose there are namespaces A and A\B respectively.

In the scope of A, can I refer a class named C within A\B just C without prepending B\?

  1. Why there are no prepending global indicator \ in namespaces? eg ) namespace \A;
  • 写回答

1条回答 默认 最新

  • drs3925 2018-03-24 00:59
    关注

    Suppose there are namespaces A and A\B respectively.

    No there is A and B is inside it.

    In the scope of A, can I refer a class named C within A\B just C without prepending B\?

    Yes if you are in A\B you can use C

    <?php
    namespace A\B;
    
    class C {}
    

    Is accessible in code which is like:

    <?php
    namespace A;
    
    $C = new B\C;
    

    Or

    <?php
    namespace A\B;
    
    $C = new C;
    

    But you cant jump to C without letting the autoloader know about B as it will look for a class in A called C, but C is in B.

    <?php
    namespace A;
    
    $C = new C;
    

    Why there are no prepending global indicator \ in namespaces? eg ) namespace \A;

    There is, you cant do:

    <?php
    namespace A\B;
    
    $C = new \A\B\C;
    
    // but not
    $C = new A\B\C;
    

    If you want a global namespace you cant do:

    <?php
    namespace;
    

    Or

    <?php
    namespace \;
    

    But you can do:

    <?php
    namespace {
        class A {}
    }
    

    Which is like no namespace at all.

    What is the relationship between the scope created by function and by namespace?

    Function scope does not have anything to do with namespaces.

    But a function declared in a namespace, is in a namespace and only accessible through its namespace.

    <?php
    namespace A;
    
    function B() {
        echo 'Value B';
    }
    
    echo B();
    // or
    echo \A\B();
    
    // this wont work
    echo \B();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?