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.
The answer was to put backslash...
should be
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
or another solution :