Home  >  Article  >  Backend Development  >  What is autoloading in php?

What is autoloading in php?

angryTom
angryTomforward
2020-01-28 23:07:142605browse

This article introduces the concept of automatic loading in PHP, and under what circumstances it is necessary to use automatic loading. Interested friends, let’s learn it together!

What is autoloading in php?

When a line of code requires a class, PHP's internal mechanism can "automatically load the class file" to satisfy the need for a class in that line. need.
When is a class needed?

1, when new an object;

2, when using a static method of a class;

3, when defining a class (B) and using another class (A) When used as a parent class;

What is autoloading in php?

Conditions and requirements

1, When a class is needed, it will Automatically call a function (default is __autoload) and pass in the name of the required class

2. A class should be saved in an independent "class file": that is, it only contains the definition of the class , no other code;

3. It is customary to have certain "rules" for naming class files, usually: class name.class.php

4. Usually, we need Store various classes in some specific directories to easily determine their location!

5, in the automatically loaded function, "fully" use the passed class name to build a suitable file path and load it;

What is autoloading in php?

Customized automatic loading function

Just now, the __autoload() function is an automatic loading function within the system. We just defined its function body.

But:

We can use more functions (customized) to achieve more flexible automatic loading!

The basic mode is:

spl_autoload_register(“函数1”); //声明“函数1”作为自动加载函数;
spl_autoload_register(“函数2”); //声明“函数2”也作为自动加载函数;
.........

Then, define these functions, just like defining the __autoload() function:

function 函数1( $class_name ){
//.......
}
function 函数2( $class_name ){
//.......
}
.............

In this way, the system will call these automatic The loading function loads the required classes until the loading is successful!

What is autoloading in php?

Recommended: "PHP Tutorial"

The above is the detailed content of What is autoloading in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete