How could I load a class from another class with autoloading

1.2k views Asked by At

How could I load a class (Connect{}) from another class (API{}) with composer autoloader.php

My files hierarchy

main.php
composer.json
src\
------ Database
---------- Connect.php
------ API
---------- API.php
vendor\
------ [...]

Composer autoload

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

main.php

require_once __DIR__.'/vendor/autoload.php';
new App\API\API();

API.php

namespace App\API;

class API {
    function __construct (){

        echo '( ';
        new App\Database\Connect; //THE CODE STOPS HERE
        echo ' )';
    }
}

Connect.php

namespace App\Database;

class Connect {
    function __construct () {
        echo('Connecting...');
    }
}

The problem is that I can't access any class from another, I know that using global variables or passing classes in __construct may be good solutions, but I need to instantiate new classes from another directly.

1

There are 1 answers

0
Husam On

The answer was to put backslash...

new App\Database\Connect;

should be

new \App\Database\Connect;

or typing use App\Database\Connect; outside the class just below the namespace, then construct class as usual $connect = new Connect().


Explanation

Inside class, namespace behavior is like this

namespace App\API;
class API {
    function __construct (){
        // WRONG : PHP will look for App\API\App\Database\Connect
        new App\Database\Connect; 

        // RIGHT : PHP will look for App\Database\Connect
        new \App\Database\Connect; 
    }
}

or another solution :

namespace App\API;
use App\Database\Connect;
class API {
    function __construct (){
        new Connect; 
    }
}