What is autoloading in php?

angryTom
Release: 2023-02-28 18:22:02
forward
2543 people have browsed it

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”也作为自动加载函数;
.........
Copy after login

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

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

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!