PHP Composer Autoloader Class not Found Exception

与世无争的帅哥 提交于 2019-12-01 15:09:01

问题


The title speaks itself. So here is my project structure:

|src
    |Database
        |Core
            |MySQL.php
        |Support
    start.php
|vendor
composer.json
index.php

MySQL.php file:

<?php
namespace Database\Core;
//Some methods here

index.php and start.php files:

//start.php file
<?php
require __DIR__ . '/../vendor/autoload.php';
?>

//index.php file
<?php
use Database\Core;
require __DIR__ . '/src/start.php';

$mysql = new MySQL(); // Gets exception Class 'MySQL' cannot found etc.
?>

And finally my composer.json autoload part:

"autoload": {
    "psr-4": "Database\\": "src/" // Also tried "src/Database" too
}

Where is the problem? I'm really tired of trying to cope with this situation. Please help guys! Thanks.


回答1:


You need to include namespace when you are initializing a class:

$mysql = new Database\Core\MySQL();

or

use Database\Core\MySQL;
$mysql = new MySQL();

See Using namespaces: Aliasing/Importing




回答2:


Aside from not using the right use statement as already mentioned, PSR-4 does not work like that. It is more of an alias. You are essentially saying that src equals Database. So to have a directory named Database in there would imply that the fully qualified namespace + class equals 'Database\Database\Core\MySQL`. You want to use PSR-0 in this case, or adjust your PSR-4 definition.



来源:https://stackoverflow.com/questions/27554364/php-composer-autoloader-class-not-found-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!