Home >Backend Development >PHP Tutorial >In-depth explanation of PHP autoload mechanism_PHP tutorial

In-depth explanation of PHP autoload mechanism_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:07:46811browse

When using PHP's OO mode to develop a system, it is usually customary to store the implementation of each class in a separate file. This will make it easy to reuse the class and will also be convenient for future maintenance. . This is also one of the basic ideas of OO design. Before PHP5, if you need to use a class, you only need to directly use include/require to include it.
The following is a practical example:

Copy the code The code is as follows:

/* Person.class.php * /
class Person {
var $name, $age;

function __construct ($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
?>

/* no_autoload.php */
require_once ("Person.class.php");

$person = new Person("Altair", 6);
var_dump ($person);
?>


In this example, no-autoload.php The file needs to use the Person class, which uses require_once to include it, and then you can use the Person class directly to instantiate an object.

However, as the scale of the project continues to expand, using this method will bring some hidden problems: if a PHP file needs to use many other classes, then a lot of require/include statements will be needed, which may cause Missing or including unnecessary class files. If a large number of files require the use of other classes, it will be a nightmare to ensure that each file contains the correct class file.

PHP5 provides a solution to this problem, which is the autoload mechanism of classes. The autoload mechanism makes it possible for PHP programs to automatically include class files only when classes are used, instead of including all class files from the beginning. This mechanism is also called lazy loading.

The following is an example of using the autoload mechanism to load the Person class:

Copy the code The code is as follows:

/* autoload. php */
function __autoload($classname) {
require_once ($classname . “class.php”);
}

$person = new Person("Altair", 6);
var_dump ($person);
?>


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327528.htmlTechArticleWhen using PHP’s OO mode to develop systems, it is usually customary to store the implementation of each class in a In a separate file, this will make it easy to reuse the class and maintain it in the future...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn