spl autoload register - What's the principle of autoloading in PHP?

876

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'));
996

Answer

Solution:

The basic idea is that you don't have to writeinclude/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, andinclude it, so the class becomes defined.

PHP can then use that class, as if you were the one who wrote theinclude 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 asProject_SubProject_Component_Name are mapped to files such asProject/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 theDoctrine_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 theDoctrine_Query_Filter_Chain class, and it is not known by PHP, theDoctrine_Core::autoload function will be called ; it'll determine that the file that should be loaded isDoctrine/Query/Filter/Chain.php ; and as that file exists, it'll be included -- which means PHP now "knows" theDoctrine_Query_Filter_Chain class.

People are also looking for solutions to the problem: xml parsing in php issue

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.