PHP classes autoload (namespaces) Part II

Ok so I made a few tests.

As a matter of fact I think it is better to use the function I wrote about in my previous post.

Turns out that I removed a couple of lines and added some more. At the end I decided to use the set_include_path because it’s more suitable for documentation purposes as well as configuration.

So after a few minutes I came up with this:

define('CLSS_PTH','path_to_classes_folder');
define('NMSPCS_PTH','path_to_namespaces_folder');
set_include_path(get_include_path() . PATH_SEPARATOR . CLSS_PTH);
set_include_path(get_include_path() . PATH_SEPARATOR . NMSPCS_PTH);

function __autoload($class){
    $class = strtolower($class);
    if(strpos($class,'\\')!==false){
        $class = preg_replace('/\\\/',DIRECTORY_SEPARATOR,$class);
    }
    $possibilities = explode(PATH_SEPARATOR, get_include_path());
    foreach($possibilities as $path){
        if(file_exists($path . DIRECTORY_SEPARATOR . $class . ".php")){
            require_once $path . DIRECTORY_SEPARATOR . $class . ".php";
        }
    }
}

So I added a path where to look for classes and namespaces, afterwards we go through all of those paths searching for the file. Works like a charm!

Tags:

Comments are closed.