Search code examples
phpautoloadmollie

Combining PHP__autoload with Mollie_API_Autoloader class


Although I know it's not appropriate to ask for ready-to-use code, I do in this case, since I'm failing to find the solution.

Trying to use native PHP __autoload function along with the Mollie_API_Autoloader class:

class Mollie_API_Autoloader
{
/**
 * @param string $class_name
 */
public static function autoload ($class_name)
{
    if (strpos($class_name, "Mollie_") === 0)
    {
        $file_name = str_replace("_", "/", $class_name);
        $file_name = realpath(dirname(__FILE__) . 
"/../../{$file_name}.php");

        if ($file_name !== false)
        {
            require $file_name;
        }
    }
}

/**
 * @return bool
 */
public static function register ()
{
    return spl_autoload_register(array(__CLASS__, "autoload"));
}

/**
 * @return bool
 */
public static function unregister ()
{
    return spl_autoload_unregister(array(__CLASS__, "autoload"));
}
}

Mollie_API_Autoloader::register();

The Mollie autoloader class affects the proper functioning of the native PHP __autoload class. Can't seem to combine these. How'd I do this?


Solution

  • __autoload() is deprecated, it was replaced by spl_autoloader_register() many years ago (on PHP 5.1.2).

    They cannot work together. __autoload() is limited and all it does, spl_autoloader_register() does better.

    Since the class you posted already uses spl_autoload_register(), all you have to do is to call

    Mollie_API_Autoloader::register()
    

    somewhere in your boostrap code.

    If your existing code uses __autoload() you can easily change it to use spl_autoload_register(). Just rename the __autoload function to something else (let's say old_autoloader) and add spl_autoload_register('old_autoloader'); after its definition.

    Check Example #1 on the documentation of spl_autoload_register() for an example.