[英]PHP Composer PSR-4 Autoloading And Sub-Namespaces, Class Not Found
This question is independent but I did ask a similar question before:- 这个问题是独立的,但我之前曾问过类似的问题:
Composer Gives Error, "Class Not Found" 作曲家给出错误,“找不到类”
The problem was solved but I failed to explain the nesting issue. 问题已解决,但我无法解释嵌套问题。 I thought it will be more appropriate to make a new question.
我认为提出一个新问题会更合适。
I searched a lot but I can't make the nesting namespaces to work with psr-4 autoloading. 我进行了很多搜索,但无法将嵌套名称空间用于psr-4自动加载。
Directory Structure:- 目录结构:
│ composer.json
│ run.php
│
├───src
│ ├───one
│ │ parentclass.php
│ │
│ └───two
│ childclass.php
│
└───vendor
│ autoload.php
│
└───composer
autoload_classmap.php
autoload_namespaces.php
autoload_psr4.php
autoload_real.php
ClassLoader.php
installed.json
LICENSE
parentclass.php:- parentclass.php:-
<?php
namespace myns\one;
abstract class parentclass
{
abstract public function abc();
}
childclass.php:- childclass.php:-
namespace myns\two;
namespace myns\one;
use myns\one\parentclass as parentclass;
class childclass extends parentclass
{
public function abc()
{
echo 'hello world';
}
}
composer.json:- composer.json:-
{
"name": "myvendor/mypackage",
"description": "nothing",
"authors": [
{
"name": "Omar Tariq",
"email": "XXXXX@gmail.com"
}
],
"require": {},
"autoload": {
"psr-4": {
"myns\\": "src/",
"myns\\one\\": "src/one/",
"myns\\two\\": "src/two/"
}
}
}
run.php:- run.php:-
<?php
require_once __DIR__ . '/vendor/autoload.php';
use myns\two\childclass as childclass;
$childclass = new childclass();
$childclass->abc();
When I run php run.php
. 当我运行
php run.php
。 It gives error:- 它给出错误:-
Fatal error: Class 'myns\two\childclass' not found in C:\wamp\...\run.php on line 7
A class can only declare one namespace in the file. 一个类只能在文件中声明一个名称空间。 By including two namespaces in
childclass.php
, you are likely overriding the first. 通过在
childclass.php
包含两个名称空间,您可能会覆盖第一个名称空间。
A full example can be seen here of using multiple namespaces, but the file only includes 1 namespace
declaration. 在这里可以看到使用多个名称空间的完整示例,但是该文件仅包含1个
namespace
声明。 That said, I suspect for your case you simply made a mistake and only need one namespace. 就是说,对于您的情况,我怀疑您只是犯了一个错误而只需要一个名称空间。
Because the file is located in myns\\two;
因为该文件位于
myns\\two;
you should use namespace myns\\two;
您应该使用
namespace myns\\two;
and remove the other. 并删除另一个。
You should only add 您只应添加
"autoload": {
"psr-4": {
"myns\\": "src/"
}
}
The other two you added may be conflicting the namespace, because you are overriding it and tell to point to the same root /src 您添加的其他两个名称可能与名称空间冲突,因为您要覆盖它并告诉指向相同的根目录/ src
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.