An in depth explanation of the PHP autoload mechanism

  • 2020-06-12 08:35:24
  • OfStack

When developing systems using PHP's OO pattern, it is common practice to store the implementation of each class in a separate file, making it easy to reuse the class and easy to maintain in the future. This is also the basic idea of OO design 1. Before PHP5, if you needed a class, you simply included it directly using include/require.
Here is a practical example:


/* Person.class.php */
<?php
class Person {
var $name, $age;
function __construct ($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
?>
/* no_autoload.php */
<?php
require_once ( " Person.class.php " );
$person = new Person( " Altair " , 6);
var_dump ($person);
?>

In this case, the ES11en-ES12en.php file needs to use the Person class, which USES require_once to include it, and then you can instantiate an object using the Person class directly.

But as the project grows in size, there are one implicit problem with using this approach: if a single PHP file requires many other classes, then many require/include sentences will be needed, which may result in missing or containing unnecessary class files. If a large number of files need to use other classes, making sure that each file contains the correct class file is a nightmare.

PHP5 provides a solution to this problem, which is the automatic loading of classes (autoload) mechanism. The autoload mechanism, also known as lazy loading, makes it possible for AN PHP program to automatically include class files when it USES the class, rather than include all class files include at the beginning of 1.

Here is an example of loading an Person class using the autoload mechanism:


/* autoload.php */
<?php
function __autoload($classname) {
require_once ($classname .  " class.php " );
}
$person = new Person( " Altair " , 6);
var_dump ($person);
?>


Related articles: