I followed Xin Xing to know that PHP's automatic loading is a framework, and the file loading mechanism is indispensable. how should we load these PHP files, so we only need to follow the rules. There are two functions in PHP to complete this function. The first one is _ autoload, which is rarely used now, instead, spl_autoload_register, which is more powerful, requires versions later than PHP5.2.1. Currently, our mainstream versions are supported, so you can use them with confidence.
In previous PHP versions, we often needed a bunch of require file names, such as configuration files, database connection files, and log files. later we had the _ autoload function, it completes all the import tasks in a function. one advantage of this function is that it can be processed programmatically. for example, you can use regular expressions to import n files at a time, to some extent, it is very convenient for us to operate. However, we must write all types in _ autoload; otherwise, automatic loading will not be well implemented.
Now with spl_autoload_register, the function is to register n loading functions. we can use this built-in function anytime, anywhere to specify the file name to be loaded. below is its function prototype:
bool spl_autoload_register ( [callback $autoload_function] )
The following code is used for practice:
First, create B. class. php with the following content:
Name. "age:". $ this-> age ;}}
Then, create a new a. php file in the directory of the same level. the content is as follows:
Getmsg ();
The reason why class B can be correctly instantiated is that when we define an instance of Class B, the system finds that the file needs to be loaded, so he went to find all the loading functions, and then B. class. php finds the definition of B and loads the file. it is worth noting that only B is here. class. php is imported, and other formats are not imported.