Question

spl_autoload_register can do this kind of job,but I don't understand how is that kind of job done?

spl_autoload_register(array('Doctrine', 'autoload'));
Was it helpful?

Solution

The basic idea is that you don't have to write include/require instructions anymore : whenever you're trying to use a non-defined class, PHP will call the autoloader.

The job of the autoloader, then, is to determine which file should be loaded, and include it, so the class becomes defined.

PHP can then use that class, as if you were the one who wrote the include instruction, that has in fact been executed in the autoloading function.


The "trick" is that the autoloading function :

  • only receives the name of the class
  • has to determine which file to load -- i.e. which file contains that class.

This is the reason for naming convention, such as the PEAR one, which says that class such as Project_SubProject_Component_Name are mapped to files such as Project/SubProject/Component/Name.php -- i.e. '_' in the class names are replaces by slashes (directories, subdirectories) on the filesystem.


For instance, if you take a look at the Doctrine_Core::autoload method, which is the one that will be called as an autoloader in your case, it contains this portion of code (after dealing with some specific cases) :

$class = self::getPath() 
            . DIRECTORY_SEPARATOR . 
            str_replace('_', DIRECTORY_SEPARATOR, $className) 
            . '.php';
if (file_exists($class)) {
    require $class;
    return true;
}
return false;

Which means the class name's is mapped to the filesystem, replacing '_' by '/', and adding a final .php to the file name.

For instance, if you're trying to use the Doctrine_Query_Filter_Chain class, and it is not known by PHP, the Doctrine_Core::autoload function will be called ; it'll determine that the file that should be loaded is Doctrine/Query/Filter/Chain.php ; and as that file exists, it'll be included -- which means PHP now "knows" the Doctrine_Query_Filter_Chain class.

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