简体   繁体   English

使用composer和PSR-0进行命名空间自动加载

[英]namespace autoloading with composer and PSR-0

I want Implemente the namespace autoloading with composer and PSR-0, and I don't know why it dosen't work. 我想使用composer和PSR-0实现命名空间自动加载,我不知道它为什么不起作用。

there is my file structure: 有我的文件结构:

src
   |app
       | world 
              | World.php

       | user
             | User.php
vendor
Test.php
composer.json

in World.php World.php中

<?php

namespace world;
class World {
    public function hello() {
        return "hello world";
    }
}
?>

in User.php User.php中

<?php
namespace user; 
class User {
    public function hello() {
        return "hello user";
    }
}
?>

in composer.json composer.json中

{
    "autoload": {
        "psr-0": {
            "my": "src/app"
        }
    }
}

and when I test this in Test.php : 当我在Test.php中测试时:

<?php
require 'vendor/autoload.php';

class Myworld {
    public function testhello() {
        $w = new my\librairie\World();
        echo $w->hello();
        $u = new my\user\User();
        echo $u->hello();
    }
}

$m = new Myworld();
$m->testhello();
?>

I get this error : 我收到此错误:

Fatal error: Class 'my\\user\\User' not found 致命错误:未找到“我的\\用户\\用户”类

Fatal error: Class 'my\\world\\World' not found 致命错误:未找到“我的\\世界\\世界”类

what I miss !? 我想念的是什么! Any advice would be welcome! 任何的建议都受欢迎! thanks. 谢谢。

There is no namespace part "my" in your definitions. 您的定义中没有名称空间部分“my”。

namespace user; 
class User {...}

This class is named \\user\\User , not \\my\\user\\User . 此类名为\\user\\User ,而不是\\my\\user\\User

The same applies to \\world\\World . 这同样适用于\\world\\World

Consequently the namespace definition in Composer is wrong. 因此,Composer中的命名空间定义是错误的。 You'd need two definitions for both user and world , both in the same directory: 在同一目录中,您需要两个userworld定义:

{
    "autoload": {
        "psr-0": {
            "user\\": "src/app",
            "world\\": "src/app"
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM