How to Use php Function spl_autoload_register
How to use php function spl_autoload_register
Today we’ll look at a php function which allows you to autoload your own functions as part of the autoloader chain. It’s an alternative to the __autoload() magic method which is being deprecated.
PHP uses the __autoload() function to load class files that it’s not sure it needs to instantiate. One of the drawbacks to this approach is that it requires you to create a separate include file for each class and the list can grow quite long. The solution to this is the spl_autoload_register() function introduced in PHP 5.1.2. This enables you to register multiple autoloaders which can be called in the order that they’re registered.
When an autoloader is called spl_autoload_register() will first check the registerNamespaces() function to see where the namespace’s base directory maps to on the file system (this is used by zend and other libraries and frameworks before real namespace support was implemented in PHP). If it can’t find the class then it will call the class loader which will try to locate the class in the directory structure that matches the naming convention of the namespace.
This is where it can be helpful to use the function property_exists() which returns TRUE even if there’s not a match or the class is not fully loaded. You can also choose to pass a closure as the second argument to the class loader to enable it to run functions within your application such as setting properties on objects prior to unserializing them.