An in-depth understanding of the automatic loading mechanism of PHP classes

Source: Internet
Author: User
Tags autoload

The first case: the contents of the file a.php are as follows

<?php
Class a{
Public Function __construct () {
echo ' FFF ';
}
}
?>

The contents of the file c.php are as follows:

<?php
function __autoload ($class)
{
$file = $class. '. php ';
if (Is_file ($file)) {
Require_once ($file);
}
}
$a = new A (); This side will automatically call __autoload, introduce the a.php file
?>

Second situation: Sometimes I want to be able to customize AutoLoad, and want to play a cooler name loader, then c.php to read as follows:

<?php
function Loader ($class)
{
$file = $class. '. php ';
if (Is_file ($file)) {
Require_once ($file);
}
}
Spl_autoload_register (' loader '); Register an automatic loading method that overwrites the original __autoload
$a = new A ();
?>

The third case: I want to be tall on a bit, using a class to manage automatic loading

<?php
Class Loader
{
public static function LoadClass ($class)
{
$file = $class. '. php ';
if (Is_file ($file)) {
Require_once ($file);
}
}
}
Spl_autoload_register (Array (' Loader ', ' loadclass '));
$a = new A ();
?>

Current is the best form.

Usually we put spl_autoload_register (*) in the portal script, which is quoted in the beginning. For example, the following discuz practice.

if (function_exist (' Spl_autoload_register ')) {
Spl_autoload_register (Array (' core ', ' autoload ')); If there is a registration function above PHP5, then registering the AutoLoad in the core class you wrote is the auto-load function
}else{
function __autoload ($class) {//If not, rewrite the PHP native function __autoload function to invoke its own core function.
Return Core::autoload ($class);
}
}

An in-depth understanding of the automatic loading mechanism of PHP classes

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.