Before the magic function _ autoload () method appears, if you want to instantiate 100 objects in a program file, you must include or require 100 class files, or you can define these 100 classes in the same class file-I believe this file will be very large.
But the _ autoload () method does not have to worry about it in the future. This class will automatically load the specified file before you instantiate the object.
The following example shows how to use the PHP magic function _ autoload.
| The Code is as follows: |
Copy code |
// Define a class ClassA named ClassA. php Class ClassA { Public function _ construct (){ Echo "ClassA load success! "; } } // Define a class ClassB. The file name is ClassB. php, and ClassB inherits ClassA Class ClassB extends ClassA { Public function _ construct (){ // Parent ::__ construct (); Echo "ClassB load success! "; } } |
After defining the classes used for testing, we compile a PHP running program file containing the _ autoload () method as follows:
| The Code is as follows: |
Copy code |
Function _ autoload ($ classname ){ $ Classpath = "./". $ classname. '. php '; If (file_exists ($ classpath )){ Require_once ($ classpath ); } Else { Echo 'class file'. $ classpath. 'not found! '; } } $ Newobj = new ClassA (); $ Newobj = new ClassB (); |
There is no problem with running this file. We can see how easy it is to use autoload ......
But I have to remind you that you must pay attention to several aspects.
1. If the class has an inheritance relationship (for example, ClassB extends ClassA), and ClassA is not in the directory of ClassB
A fatal error occurs when ClassB is instantiated using the _ autoload magic function:
| The Code is as follows: |
Copy code |
| Fatal error: Class 'classd' not found in ...... ClassB. php on line 2, |
Solution: Put all classes with extends relationships in the same file directory, or manually include the inherited classes in the file when instantiating an inheritance class;
2. Note that the class name and class file name must be consistent to facilitate the use of magic function _ autoload;
Other things to be aware:
3. This method is invalid when you run the PHP script in CLI mode;
4. If your class name is related to user input -- or dependent on user input, check the input file name, for example :.. /. /Such a file name is very dangerous.