Question

I'm looking for __autoload magic method inside the YiiBase class, but it isn't. In the official docs said that public static function autoload($className) is

Class autoload loader. This method is provided to be invoked within an __autoload() magic method.

I'm confused. What class of yii framework contains __autoload magic method? Is it possible to get an example with a component class autoloading?

Was it helpful?

Solution

Yii uses the spl_autoload_register function to set the autoloader function. The spl_autoload_register was introduced in PHP 5.1.2 and makes it possible for us to register multiple autoload functions. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once. In Yii you can find this in YiiBase.php, just after the definition of the YiiBase class, at the very end of the file:

spl_autoload_register(array('YiiBase','autoload'));

Where autoload is a static method definied in the YiiBase class.

Using spl_autoload_register instead of the __autoload() magic function is good for us, because this way Yii's autoloader does not conflict with our own or with another thrid-party's autoloader. The YiiBase class also defines a registerAutoloader function to register another autoloader function before or after Yii's autoloader in the chain. If you take a look at its code, it is pretty straightforward what it does:

public static function registerAutoloader($callback, $append=false)
{
    if($append)
    {
        self::$enableIncludePath=false;
        spl_autoload_register($callback);
    }
    else
    {
        spl_autoload_unregister(array('YiiBase','autoload'));
        spl_autoload_register($callback);
        spl_autoload_register(array('YiiBase','autoload'));
    }
}

It really just uses spl_autoload_register and/or spl_autoload_unregister (yes, you can also unregister an autoload function!), to put the new autoloader before or after Yii's autoloader, because spl_autoload_register always registers the new autoloader at the end of the chain.

OTHER TIPS

I think that Yii tries to autoload a class whenever you reference it. Yii is simply making use of PHP's __autoload() function. It's a magic method like __get() or __set().

For example, when you write $foo = new Foo(); and class Foo has not been loaded yet, you will get an Error.

But you can prevent that if you define an __autoload($classname) function before. This way, instead of throwing an Error, PHP will first try to run the __autoload($classname) function. In that function, you can do things like: include the variable $classname and so on.

There's more information here: http://www.php.net/manual/en/function.autoload.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top