Hi all.

Does anyone have a good autoloader script for namespace classes ?

Namespace is identical to the file structure.

Recommended Answers

All 3 Replies

ok, noted the above is probably a bad post, so to extend:

I have gone trhough many samples from goolge, one i have come across is the following:

spl_autoload_register(function ($className) {

    # Usually I would just concatenate directly to $file variable below
    # this is just for easy viewing
        $dir = __DIR__;

    // replace namespace separator with directory separator (prolly not required)
        $className = strtr($className, '\\', $ds);

    // get full name of file containing the required class
        $file = "{$dir}{$ds}{$classname}.php";

    // get file if it is readable
        if (is_readable($file))
            require_once $file;

Which seems fine - if you are calling the files from the same, or below folder structure.

My folder structure mimicks that of my namespace structure as per PSR-0

So my question:

How can this be adopted to be used globally?


Many thanks.

So from the link i have opted for, what i am asuming, the easier option:

file will be called autoLoader.php and added to the .ini include PATH to load in.

// autoload functions only
// loaded in order

#!! IMPORTANT !! -> Database connection load
function autoloadDataBase($className){
    $filename = 'classLib/dataBase/' . $className . '.php';

        include $filename;

function autoloadCRUD($className){

    $filename = "classLib/CRUD/" . $className .'.php';

        include $filename;


function autoloadRSS($className){

    $filename = "classLib/RSS/" . $className .'.php';

        include $filename;




I am guessing there are many ways to tidy this up, if anyone can suggest i am open to suggestions :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.