Using namespaces with classes created from a variable

后端 未结 1 612
面向向阳花
面向向阳花 2020-11-28 16:48

So I created these two classes

//Quarter.php
namespace Resources;
class Quarter {
    ...
}


//Epoch.php
namespace Resources;
class Epoch {

    public stat         


        
相关标签:
1条回答
  • 2020-11-28 17:08

    Because strings can be passed around from one namespace to another. That makes name resolution ambiguous at best and easily introduces weird problems.

    namespace Foo;
    
    $class = 'Baz';
    
    namespace Bar;
    
    new $class;  // what class will be instantiated?
    

    A literal in a certain namespace does not have this problem:

    namespace Foo;
    
    new Baz;     // can't be moved, it's unequivocally \Foo\Baz
    

    Therefore, all "string class names" are always absolute and need to be written as FQN:

    $class = 'Foo\Baz';
    

    (Note: no leading \.)

    You can use this as shorthand, sort of equivalent to a self-referential self in classes:

    $class = __NAMESPACE__ . '\Baz';
    
    0 讨论(0)
提交回复
热议问题