Php magic method _ autoload (). If you need it, refer to it. The _ autoload () method is a special function. it is not a class method, but a separate function and is declared outside the class, it will be called in the instantiation of a class that has not been declared. Example:
- Require_once ('test/A. php ');
- Require_once ('test/B. php ');
- Require_once ('test/C. php ');
- If (condition ){
- $ A = new ();
- $ B = new B ();
- $ C = new C ();
- } Else if (condition B ){
- $ A = newA ();
- $ B = new B ();
- }
In this case, A problem occurs. when class B is instantiated under Condition B, the and C files do not need to be referenced. Therefore, some resources are wasted to compile class, C two "useless classes", so we can use the _ autoload () function to solve this problem.
- Function _ autoload ($ className ){
- $ FilePath = "test/{$ className}. php ";
- If (is_readable ($ filePath )){
- Require ($ filePath );
- }
- }
- If (condition ){
- $ A = new ();
- $ B = new B ();
- $ C = new C ();
- } Else if (condition B ){
- $ A = newA ();
- $ B = new B ();
- }
When the php engine uses Class A for the first time but cannot find it, the _ autoload method is automatically called and the class name "A" is passed in as A parameter. So what we need to do is find the corresponding file based on the class name and include it. if our method cannot be found, the php engine will report an error. Note: only require can be used here, because once included, when the php engine encounters Class A, it will not call _ autoload, but directly use Class A in the memory, does not cause multiple inclusion. Now let's talk about the running mechanism of autoload. When PHP instantiates an object (in fact, this is the case when the interface is implemented, using static variables in a class constant or class, and calling static methods in the class ), first, the system checks whether the class (or interface) exists. if it does not exist, it tries to use the autoload mechanism to load the class. The main execution process of the autoload mechanism is: (1) Check whether the global variable function pointer autoload_func of the executor is NULL. (2) if autoload_func = NULL, check whether the _ autoload () function is defined in the system. if not, report an error and exit. (3) If the _ autoload () function is defined, execute _ autoload () to load the class and return the loading result. (4) If autoload_func is not NULL, the autoload_func pointer is directly executed to load the class. In this case, the _ autoload () function is not defined. |