When using the ThinkPHP framework, view its source code to use the functions _ autoload and apl_autoload_register. These two functions are used for automatic loading.
The main function is to trigger these two functions to load the file that has not been loaded.
Php's _ autoload function is a magic function. Before this function appears, if a php file references 100 objects, this file requires the use of include or require to introduce 100 class files, which will lead to a huge PHP file. So we have the _ autoload function.
_ When will the autoload function be called?
When the new keyword is used in the PHP file to instantiate an object, if the class is not defined in this PHP file, the _ autoload function is triggered. In this case, you can introduce the PHP file that defines the class, then, the instance can be instantiated successfully. (Note: if the object to be instantiated has already found the definition of this class in this file, the _ autoload function will not be triggered)
1234 |
#Animal.php
<!--?php class Animal{} ?--> |
12345678910111213 |
#main.php <!--?php function __autoload($classname){ $classpath = "{$classname}.php" ; if (file_exists($classpath)){ require_once($classpath); } else { echo $classpath. " not be found!" ; } } $ani = new Animal(); ?--> |
Run php main. php as shown in the preceding two files.
(1) When running to new Animal (), the class Animal is not defined;
(2) The _ autoload function is triggered, which introduces the Animal. php file;
(3) The instance is instantiated successfully.
Now, I understand the function of the _ autoload function. Let's take a look at the function of the spl_autoload_register function.
The spl_autoload_register function is used to replace the User-Defined Function settings with the _ autoload function (NOTE: When both _ autoload and spl_autoload_register appear in the file, take spl_autoload_register as the standard)
Changing main. php to the following also has the same effect:
12345678910111213 |
#main.php <!--?php
function myLoad($classname){ $classpath = "{$classname}.php" ; if (file_exists($classpath)){ require_once($classpath); } else { echo $classpath. " not be found!" ; } } spl_autoload_register( "myLoad" ); $ani = new Animal(); ?--> |