Automatic loading of PHP:
Before php5, we need to use a class or class method, which must include or require, before you can use, each time with a class, you have to write an include, trouble
PHP author want to Simple point, it is best to reference a class, if there is no include in, the system can automatically find the class, automatically introduced ~
Thus: the __autoload () function was born.
It is usually placed in the application entry class, such as Discuz, in the class_core.php.
Let's start with plain examples:
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);
}
}
This paragraph is thrown at the front of the entrance document, nature is very good ~
Reprint: http://www.cnblogs.com/zhongyuan/p/3583201.html
Automatic loading mechanism for PHP classes