PHP class automatic loading method, PHP Loading Method
Automatic class loading means that you do not need to "introduce" class files on the external page, but the program will dynamically load the required class files as needed.
Method 1: Use the _ autoload magic Function
When a program needs a class, it will call this function. We need to define this function and write the general statements for loading class files.
<? Php // The required class is automatically called and a class name will be passed in. In this case, the file name is 21A. class. php, Class Name: A function _ autoload ($ className) {require ". /21 ". $ className. ". class. php ";}$ o1 = new A (); $ o1-> v1 = 10; echo" <br/> v1 :". $ o1-> v1;?>
Method 2:Use the spl_autoload_register Function
The function functions multiple functions that can be used to replace the autoload function. The syntax is as follows: spl_autoload_regist ("function name 1"); If spl_autoload_register is used, autoload becomes invalid.
<? Php // register two function names for automatic loading: spl_autoload_register ('auto1'); spl_autoload_register ('auto2'); function auto1 ($ className) {$ file = ". /21 ". $ className. ". class. php "; if (file_exists ($ file) {require ". /21 ". $ className. ". class. php ";}} function auto1 ($ className) {$ file = ". /22 ". $ className. ". class. php "; if (file_exists ($ file) {require ". /22 ". $ className. ". class. php ";}}// if a ray is required, but this page has not been recorded, it will call auto1 and auto2 in turn, knowing to find this Class file and load?>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.