Before the magic function __autoload() method appeared in PHP, if you wanted to instantiate 100 objects in a program file, then you had to include 100 class files using include or require, or you defined these 100 classes in the same program file. In a class file - I believe this file will be very large.
But with the __autoload() method, you don’t have to worry about it in the future. This class will automatically load the specified file before you instantiate the object.
Let’s take a look at the specific usage through an example, and explain later what you should pay attention to when using the PHP magic function __autoload.
The code is as follows
|
Copy code
|
||||||||
class ClassA{ }
class ClassB extends ClassA { public function __construct(){//parent ::__construct(); echo "ClassB load success!"; }
|
The code is as follows |
Copy code
|
The operation of this file is There is no problem at all, which shows how easy to use autoload is, haha... 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 where ClassB is located When you use the __autoload magic function to instantiate ClassB, you will receive a fatal error: Solution: Put all classes with extends relationship in the same file directory, or manually include the inherited class in the file when instantiating an inherited class; 2 , Another thing to note is that the class name and the file name of the class must be consistent to make it easier to use the magic function __autoload; Other things to note: 3. Run PHP in CLI mode This method is invalid for scripts; 4. If your class name is related to user input - or depends on user input, be sure to check the input file name, for example: .././ like this The file name is very dangerous.
http://www.bkjia.com/PHPjc/444710.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444710.htmlTechArticlePHP Before the magic function __autoload() method appeared, if you wanted to instantiate 100 in a program file Object, then you must use include or require to include 100 class files, or...
|