When developing a system using the OO pattern in PHP, it is often customary to store implementations of each class in a separate file, which makes it easy to reuse classes and facilitates future maintenance. This is also one of the basic ideas of OO design. Before PHP5, if you need to use a class, just use include/require to include it in it.
The following is a practical example:
Copy Code code as follows:
* 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 no-autoload.php file needs to use the person class, which uses require_once to include it, and then it can instantiate an object directly using the person class.
But as the scale of the project expands, there are some hidden problems with this approach: if a PHP file needs to use many other classes, then a lot of require/include statements are required, which may cause omission or include unnecessary class files. If a large number of files require the use of other classes, it must be a nightmare to ensure that each file contains the correct class file.
PHP5 provides a solution to this problem, which is the automatic loading (autoload) mechanism of the class. The autoload mechanism can make it possible for a PHP program to automatically include class files when using classes, rather than including all of the class files in the first place, a mechanism known as lazy loading.
The following is an example of using the autoload mechanism to load the person class:
Copy Code code as follows:
* autoload.php * *
<?php
function __autoload ($classname) {
Require_once ($classname. "class.php");
}
$person = new Person ("Altair", 6);
Var_dump ($person);
?>