Composer 给出错误,“找不到类"

我使用的是 Windows 10.在根目录中创建文件夹 src 后,我在其中创建了两个文件.

I'm using Windows 10. After making a folder src in the root directory I created two files in it.

目录结构(在运行composer install之前):

Directory Structure (Before running composer install):

│
├── composer.json
├── run.php
│
└── src
     ├── childclass.php
     └── parentclass.php

根目录下的两个文件:

composer.json:

composer.json:

{
    "name": "myvendor/mypackage",
    "description": "nothing",
    "authors": [
        {
            "name": "Omar Tariq",
            "email": "XXXXX@gmail.com"
        }
    ],
    "require": {},
    "autoload": {
        "psr-4": {
            "myns\": "src/"
        }
    }
}

运行.php:

<?php

require_once __DIR__ . '/vendor/autoload.php';

use mynschildclass as childclass;

$childclass = new childclass();
$childclass->abc();

src文件夹中的两个文件:

Two files in the src folder:

childclass.php:

childclass.php:

<?php

require_once 'parentclass.php';

use mynsparentclass as parentclass;

class childclass extends parentclass
{
    public function abc()
    {
        echo 'hello world';
    }
}

父类.php:

<?php

namespace myns;

abstract class parentclass
{
    abstract public function abc();
}

运行composer install后的目录结构:

│
├── composer.json
├── run.php
│
├── src
│    ├── childclass.php
│    └── parentclass.php
│
└── vendor
     ├── autoload.php
     │
     └── composer
          ├── autoload_classmap.php
          ├── autoload_namespaces.php
          ├── autoload_psr4.php
          ├── autoload_real.php
          ├── ClassLoader.php
          ├── installed.json
          └── LICENSE

现在,当我跑步时:

php run.php

我收到此错误:

致命错误:第 7 行的 C:wamp...un.php 中找不到类 'mynschildclass'

Fatal error: Class 'mynschildclass' not found in C:wamp...un.php on line 7

推荐答案

composer.json 中,您为 src 文件夹定义了使用 myns 命名空间,所以在你的 childclass.php 你应该使用

In composer.json you defined that for src folder you use myns namespace, so in your childclass.php you should use

namespace myns;

也不必加:

require_once 'parentclass.php';

use mynsparentclass as parentclass;

所以你的 childclass.php 应该是这样的:

so your childclass.php should look like this:

<?php

namespace myns;

class childclass extends parentclass
{
    public function abc()
    {
        echo 'hello world';
    }
}

另外在 run.php 文件中你可以替换:

In addition in run.php file you might replace:

use mynschildclass as childclass;

进入

use mynschildclass;

如果您不想为类使用其他名称,则不需要使用 as.

You don't need to use as if you don't want to use other name for class.

您还应该考虑使用带有大写字母(Studly caps)的命名空间,并且对于类也是如此.代替 myns 使用 MyNs,代替 parentclass 使用 ParentClass.您应该查看 PSR-1 编码标准 和 PSR-2 编码标准 遵循最佳编码实践.

You should also consider using namespaces with capital letter (Studly caps) and the same for classes. Instead of myns use MyNs, instead of parentclass use ParentClass. You should look at PSR-1 coding standard and PSR-2 coding standard to follow best coding practises.

相关文章