简体   繁体   中英

PSR-4 not loading my project classes

I'm using Composer's PSR-4 to autoload classes, but it won't load my classes. Every time I try to use one of my classes the app dies without any error, even though it should display error.

Here is my file structure:

/
│   composer.lock
│   composer.json
│   index.php
├───src
│       Array.php
│       File.php
├───vendor
        ...

composer.json - autoload part

"autoload": {
    "psr-4": {
        "FileManager\\": "src"
    }
}

Start of index.php

<?php

require(__DIR__ . '/vendor/autoload.php');

var_dump(class_exists('Array'), class_exists('Array', false));
var_dump(class_exists('File'), class_exists('File', false));

And it dumps this:

bool(false)
bool(false)
bool(false)
bool(false)

If I add

use FileManager\Array;

it will die instantly. If I add

use FileManager\File;

it won't die, but it won't recognize File class either.

I have ran

$ composer dumpautoload

Can somebody help me with this?

The problem is that you are passing string s to class_exists() .

If you use string values to reference class names, you will need to use the fully-qualified class name .

<?php

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

var_dump(
    class_exists('FileManager\ArrayUtil'),
    class_exists('FileManager\File')
);

Alternatively, you can use the class keyword (requires at least PHP 5.5):

<?php

use FileManager\ArrayUtil;
use FileManager\File;

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

var_dump(
    class_exists(ArrayUtil::class),
    class_exists(File::class)
);

For reference, see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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