In-depth understanding of the automatic loading mechanism of PHP classes and deep understanding of php Loading
Php automatic loading:
Before php5, we need to use a class or class method, which must be included or require before it can be used. Every time we use a class, we need to write an include statement, which is troublesome.
The php author wants to make it simple. It is best to reference a class. If no include is included, the system can automatically find the class and introduce it automatically ~
So the :__ autoload () function came into being.
It is usually placed in the application entry class, such as discuz, and in class_core.php.
Let's give a simple example:
First case: The content in file A. php is as follows:
<?phpclass A{ public function __construct(){ echo 'fff'; }}?>
The content in file C. php is as follows:
<? Php function _ autoload ($ class) {$ file = $ class. '. php '; if (is_file ($ file) {require_once ($ file) ;}}$ a = new A (); // This will automatically call _ autoload, introduce. PHP file?>
Case 2:Sometimes I want to customize autoload and a cooler name loader, C. php is changed to the following:
<? Phpfunction loader ($ class) {$ file = $ class. '. php '; if (is_file ($ file) {require_once ($ file) ;}} spl_autoload_register ('loader'); // register an automatic loading method, overwrite the original _ autoload $ a = new A ();?>
Case 3: I want to use 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();?>
The current format is the best.
Generally, we place spl_autoload_register (*) In the portal script, which is referenced from the beginning. For example, the following discuz practice.
If (function_exist ('spl _ autoload_register ') {spl_autoload_register (array ('core', 'autoload'); // if it is php5 or above, a registration function exists, then, register the autoload function in the core class you wrote as the automatic loading function} else {function _ autoload ($ class) {// if not, rewrite the php native function _ autoload function, let it call functions in its core. Return core: autoload ($ class );}}
This part is thrown at the beginning of the entrance file, which is naturally excellent ~
The above in-depth understanding of the automatic loading mechanism of PHP class is all the content shared by the editor. I hope to give you a reference and support for the help house.