Deep into PHP autoload mechanism of detailed _php skills

Source: Internet
Author: User
Tags autoload

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);
?>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.