Search code examples
phpautoloader

Autoloader appears to be omniscient | Nested includes not needed


I use this simple autoloader code:

function __autoload( $class_name ) { include 'class.' . $class_name . '.php'; }

and I make this call new SDB();

SDB actually inherits from SDBOne which I never include...yet the auto-loader loads it.

This means it knows to load modules nested / included in other modules.

So from the looks of it I never need to require or include anything if I use the auto-loader.

However, if I use a stand alone module where there is no auto-loader, I then need to include the class it inherits from.

Should I use

require,

require_once,

include,

include_once.

I would guess to go with require_once because I want an error not a warning...plus when I use the code with the autoloader I don't want it loaded twice.

Basically I have 2 types of use for SDB : one with the autoloader present and one with out.

Reference

http://php.net/manual/en/language.oop5.autoload.php


Solution

  • You are correct, require_once would be the correct way to include a parent class or dependent class in one file. That way if its included multiple times, the require_once prevents errors that would arise from redeclaring a class.

    The autoloader is autoloading SDBOne automatically because it needs that class defined before it can extend SDB from it. The same thing is happening to autoload the parent class on demand as happens when you try to load the inherited class.

    Also, you should consider switching to spl_autoload_register so that your code will work well with other code that may use an autoloader. The SPL autoloader supports multiple autoloaders and creates a stack in the order they are registered. This way if the first autoloader doesn't satisfy the requirement, it keeps trying subsequently registered autoloaders until the class is loaded or cannot be found.

    Another note on preventing errors, you may want to change your autoload function as follows:

    function __autoload( $class_name ) { 
        $file = 'class.' . $class_name . '.php';
        if (file_exists($file)) {
            include $file;
        }
    }
    

    Because if the class being autoloaded doesn't exist, you will get errors about including a non-existent file. This is especially important when using spl_autoload_register; you don't want your autoloader to emit unnecessary warnings about missing files if another autoloader will be ultimately responsible for loading the class in question.

    Hope that helps.