PSR-4 not loading my project classes

912 views Asked by At

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?

1

There are 1 answers

0
localheinz On

The problem is that you are passing strings 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: