Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

varundavda's avatar

Autoload Classes in Core PHP

Hello all,

I am trying to understand the concept of autoloading using core PHP, not any framework.

I have a file named Donor.php which is under App -> src -> Contacts.

Here is the code of Donor.php

<?php namespace src\Contacts;

class Donor{ 

    public function __construct()
    {
        return ('Loaded');
    }

}

I have another file named namespace.php, which is immediate child of the root directory. The code of namespace.php looks like this.

<?php 

use src\Contacts;

new \app\Contacts\Donor;

My composer.json file looks like this.

{
    "autoload": {
        "psr-4":{
            "app\\" : "app/src"
        }
    }
}

Here is my full folder structure.

basic
   app
     src
          Billing
          Contacts
                Donor.php
   vendor
  composer.json
  namespace.php

Now wehenver i run namespace.php it always gives Fatal error: Class 'app\Contacts\Donor' not found in C:\xampp\htdocs\basic\namespace.php on line 5

Can anyone explain me what i am doing wrong here?

0 likes
5 replies
spekkionu's avatar

Try changing this in your composer.json

{
    "autoload": {
        "psr-4":{
            "app\\" : "app/src"
        }
    }
}

to this

{
    "autoload": {
        "psr-4":{
            "src\\" : "app/src/"
        }
    }
}

Then run composer dumpautoload

Also change this

<?php 

use src\Contacts;

new \app\Contacts\Donor;

to this

<?php 

use src\Contacts\Donor;

new Donor;
spekkionu's avatar
Level 48

You are including the composer autoloader in you script correct? If not you'll need to add that.

require 'path/to/vendor/autoload.php'
1 like
zachleigh's avatar

Try this:

new app\Contacts\Donor;

You have a slash () in front of app which tells php to look in the global namespace.

varundavda's avatar

@spekkionu @zachleigh Thank you.

As i work in laravel i did not knew to require autoload.php in core. As laravel does it by default.

It is working now.

Thank you

Please or to participate in this conversation.