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'));
Answer
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 :
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 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 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) :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, 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.