English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PHP's automatic loading:
In PHP5In the past, if we wanted to use a class or a method of a class, we had to include or require it first before we could use it. It was麻烦 to write an include for each class used.
PHP authors wanted it to be simpler, ideally, when referencing a class, if the class has not been included yet, the system can automatically find the class and import it automatically~
Thus, the __autoload() function came into being.
It is usually placed in the entry class of the application, for example, in discuz, it is placed in class_core.php.
Let's take a simple example first:
The first caseThe content of file A.php is as follows
<?php class A{ public function __construct(){ echo 'fff'; } } ?>
The content of file C.php is 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, and import the A.php file ?>
The second case:Sometimes I wish I could customize autoload and want to call it a cooler name loader, then C.php is changed to the following:
<?php function loader($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register('loader'); //Register an automatic loading method to override the original __autoload $a = new A(); ?>
The third caseI hope it can be more sophisticated, 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(); ?>
This is the best form at present.
Generally, we use spl_autoload_register(*It is placed in the entry script, that is, it is referenced at the beginning. For example, the following discuz practice.
if(function_exist('spl_autoload_register')){ spl_autoload_register(array('core','autoload')); //If it is php5As mentioned above, if there is a registered function, register the autoload of the core class written by yourself as the automatic loading function. } function __autoload($class){ //If not, rewrite the php native function __autoload to call its own core function. return core::autoload($class); } }
This part is naturally very good if it is placed at the beginning of the entry file.
This article, a deep understanding of the automatic loading mechanism of PHP classes, is all the content the editor shares with everyone. Hope it can be a reference for everyone, and I also hope everyone will support the Shouting Tutorial.