Zend PHP 7 Certification – OOP – Autoload

This post covers the Autoload section of the OOP chapter when studying for the Zend PHP 7 Certification.

In order to use a class within PHP, the class must be included by using include or require. With multiple classes, one of the biggest annoyances is having to write a long list of needed includes, one for each class, at the beginning of each PHP script.

PHP has a solution involving autoloading classes using a couple of functions, one of which is to use spl_autoload_register().

This function gives you the ability to register any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined.

The three parameters of spl_autoload_register() are as follows: The autoload function being registered, a $throw boolean specifying whether exceptions should be thrown when the autoload function parameter cannot be registered, and a $prepend boolean, when if true, prepends the autoloader on the autoload queue instead of appending it.

Although there is an __autoload() function that gets executed whenever there is an attempt to use a class or interface that has not been defined, it is preferred to use the spl_autoload_register() function.

This is because it is a more flexible alternative (enabling for any number of autoloaders to be specified in the application.

An example of how __autoload() works can be seen below. Note the double underscore prefix telling us the method is a PHP magic method. The argument passed in __autoload() is the name of the missing class you’re looking to include.

// myClass.php
<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfully!";
    }
}

// index.php
<?php
// We've written this code where we need
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// We've called a class
$obj = new myClass();

The spl_autoload_register() function registers a function as an __autoload() implementation.

In the following example, the my_autoloader() function is used as an __autoload() implementation.

function my_autoloader($class) {
    include '/' . $class . '.php';
}

spl_autoload_register('my_autoloader');

$class = new className();

An anonymous function can also be used.

spl_autoload_register(function ($class) {
    include '/' . $class . '.php';
});

Note that there is also a spl_autoload_unregister() function. This unregisters a given function as an __autoload() implementation.

A useful snippet of code to unregister all functions can be seen below.

<?php
$functions = spl_autoload_functions();
foreach($functions as $function) {
    spl_autoload_unregister($function);
}

View the other sections:

Note: This article is based on PHP version 7.0.