Why use spl_autoload_register

In PHP development, we often need to reference some class libraries, usually through require, then we will find that when using some frameworks, we can instantiate various classes without writing require. How is this done?

It is through __autoload() and spl_autoload_register()

__autoload($class_name) will automatically call this function when the class is not found, and automatically assign the parameter to the unreferenced class name

For example $a = new API();

At this time, the API is not referenced, so the __autoload function will be called, and the value of $class_name will become 'API'. We can do this by

Write require $class_name in the __autoload function to achieve the purpose of automatic reference.

For spl_autoload_register(), multiple autoload functions can be registered, and the default __autoload function will be invalid.

Then we will think, why not write it all in the __autoload function.

The reasons are as follows:

1. If your classes are placed in different directories, the function logic in __autoload will become more and more complicated.

2. If you reference a third-party class library, if spl_autoload_register() is used in the third-party class library, your autoload function will be invalid.

3. Using spl_autoload_register() will make the logic clearer, and each class library can have its own autoload method.

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324080859&siteId=291194637