Automatic loading of PHP:
Before PHP5, we have to use a class or class method, which must include or require, and then use, each time with a class, need to write an include, trouble
PHP authors want to be simple, it is best to reference a class, if the current does not include in, the system can automatically find the class, automatic introduction ~
So: the __autoload () function came into being.
It is usually placed inside the application entry class, such as Discuz, in the class_core.php.
Let's start with the plain examples:
In the first case : The contents of the document 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 will automatically invoke __autoload and introduce a.php files
?>
The second scenario: 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 '); Registers an automatic loading method, overwriting the original __autoload
$a = new A ();
>
A third case : I want to be tall, with 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 place the spl_autoload_register (*) in the entry script, which is quoted at the outset. For example, the following discuz approach.
if (function_exist (' Spl_autoload_register ')) {
spl_autoload_register (array (' core ', ' autoload '));//If it is php5 above, There is a registration function, then register the AutoLoad in the core class that you write to automatically load functions
}else{function
__autoload ($class) { //if not, rewrite PHP native function __ AutoLoad function to call its own core middle function. Return
core::autoload ($class);
}
}
This paragraph is thrown at the front of the entry file, which is naturally very good.
The above in-depth understanding of the PHP class automatic loading mechanism is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.