Daria
Daria

Reputation: 861

PHP cannot autoload classes

We used to include only classes that are stored in a {project_root}/includes folder. And we used autoload function to include classes we need in our apps. Now I wanted to use some library and I faced a problem:

1) Autoload:

// {project_root}/includes/autoLoad.php
// There is a global_connfig.php file that loads by directive in php.ini 
// auto_prepend_file = /var/www/global_config.php which includes autoload.php file and sets the include path to {project_root}/includes
function __autoload($classname){
    include "$classname.php";
}

2) Code I wanted to use:

//just an example from the monolog reference
// I put Monolog folder with it's subfolders in {project_root}/includes
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger("name");
$log->pushHandler(new StreamHandler(LOGSPATH . '/monolog', Logger::WARNING));


$log->warning('Foo');
$log->error('Bar');

3) Errors:

Warning: include(Monolog\Logger.php): failed to open stream: No such file or
directory in {project_root}/includes/autoLoad.php

I tried to use something like this: autoloading classes in subfolders, but still getting Class 'Monolog\Logger' not found

question updated

Upvotes: 2

Views: 514

Answers (1)

Thibault
Thibault

Reputation: 1596

Try this autoload function instead :

function __autoload($classname)
{                                      
    $filename = str_replace("\\", "/", $classname).".php";       
    include __DIR__."/$filename";                                     
}  
  • It replaces \ with / to match paths
  • It searches from the includes/ directory.

You might also consider adding the includes/ path to your include_path php directive :

set_include_path(get_include_path() . PATH_SEPARATOR . "{project_root}/includes");

Upvotes: 1

Related Questions