PHP _ autoload function (automatic loading of class files) usage. This is also one of the basic ideas of OO design. Before using PHP5, if you need to use a class, you only need to directly use javasderequire to include it. The following is a practical example: this is also one of the basic ideas of OO design. Before using PHP5, to use a class, you only need to directly include it using include/require. The following is an actual example:
The code is as follows:
Class ClassA {
Public function _ construct (){
Echo "ClassA load success !";
}
}
// Define a class ClassA named ClassA. php
Class ClassA {
Public function _ construct (){
Echo "ClassA load success !";
}
}
Class ClassB extends ClassA {
Public function _ construct (){
// Parent ::__ construct ();
Echo "ClassB 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:
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:
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.
Bytes. Before using PHP5, to use a class, you only need to directly include it using include/require. The following is an example :...