Cannot find Class with PHP Namespace

前端 未结 5 1757
深忆病人
深忆病人 2020-12-09 08:31

I posted some questions previously regarding the use of Namespaces in PHP and from what I got, this example code I have below should be working.

However I am getting

5条回答
  •  渐次进展
    2020-12-09 09:04

    Its not that good idea to name the namespace, like the class, because it is confusing (and I think this is what happens here). There moment you define the alias via use Controller this referenes to either a class \Controller, or the namespace \Controller, but your class, because it is within the namespace, is named \Controller\Controller 1

    use Controller;
    $class = new Controller\Controller;
    

    or

    $class = new \Controller\Controller;
    

    or

    use Controller\Controller;
    $class = new Controller;
    

    The idea is, that the moment you try to access a class with its relative name it tries to map the "first part" against any alias defined using use (remeber use MyClass is the same as use MyClass as MyClass. The thing after as is the alias).

    namespace MyNamespace\MyPackage\SomeComponent\And\So\On {
      class MyClass {}
    }
    namespace Another {
      use MyNamespace\MyPackage\SomeComponent; // as SomeComponent
      $class =              new SomeComponent\An\So\On\MyClass;
    }
    

    As you can see PHP finds SomeComponent as the first part and maps it against the SomeComponent-alias the line above.

    You can read more about it in the manual about namespaces.

    1 Its called "Full-qualified classname", if you name a class with its complete name.

提交回复
热议问题