php magic method __autoload(), friends in need can refer to it. __autoload() method is a special function. It is not a class method, but a separate function. It is declared outside the class and will be called when instantiating a class that has not been declared yet.
A problem will arise when writing like this. When class B is instantiated under condition B, there is actually no need to reference files A and C. Therefore, the method in the chestnut will waste some resources to compile two "useless files" A and C. "class"; so at this time we can use the __autoload() function to solve this problem.
When the php engine uses class A for the first time but cannot find it, it will automatically call the __autoload method and pass in the class name "A" as a parameter. Therefore, what we need to do is to find the corresponding file according to the class name and include it. If our method cannot find it, then the PHP engine will report an error. Note that you can only use require here, because once it is included, when the PHP engine encounters class A again, it will not call __autoload, but directly use class A in the memory, which will not cause multiple inclusions. Now let’s talk about the operating mechanism of autoload. When PHP instantiates an object (actually when implementing an interface, using class constants or static variables in a class, or calling static methods in a class), it will first search in the system. Whether the class (or interface) exists, if not, try to use the autoload mechanism to load the class. The main execution process of the autoload mechanism is: (1) Check whether the executor global variable function pointer autoload_func is NULL. |