search
HomeWeb Front-endJS TutorialDetailed interpretation of PHP automatic loading autoload and namespace

PHP’s automatic loading means that when we load an instantiated class, we don’t need to manually write require to import the class.php file. The program automatically loads and imports it for us. This article mainly introduces PHP automatic loading autoload and naming. For empty applications, friends who need it can refer to

. Let me first tell you what a namespace is.

"What is a namespace? Broadly speaking, a namespace is a way to encapsulate things. This abstract concept can be seen in many places. For example, in the operating system, directories are used to File grouping plays the role of a namespace for files in a directory. For example, the file foo.txt can exist in the directories /home/greg and /home/other at the same time, but in the same directory There cannot be two foo.txt files in. In addition, when accessing the foo.txt file outside the directory /home/greg, we must put the directory name and directory separator before the file name to get /home/greg/foo.txt. This principle is applied to the field of programming and is the concept of namespace."

The automatic loading of PHP means that when we load the instantiated class, we do not need to manually write require to import the class.php file, the program automatically helps We load and import it. With the namespace specification, we can easily handle the loading and calling of different classes in complex systems.

1. The principle of automatic loading and the use of __autoload

The principle of automatic loading is that when we instantiate a class, If PHP cannot find this class, it will automatically call the __autoload($class_name) method in this file, and our new class_name will become the parameter of this method. So in this method, we can require the corresponding path class file based on the various judgments and divisions we need new class_name to achieve automatic loading.

Let’s first look at the automatic call of __autoload(), for example:

index.php

<?php 
$db = new Db();

If we do not manually import the Db class, the program may An error was reported, saying that this class could not be found:

Fatal error: Uncaught Error: Class 'DB' not found in D:\web\helloweba\demo\2017\autoload\index.php:2 Stack trace: # 0 {main} thrown in D:\web\helloweba\demo\2017\autoload\index.php on line 2

So, let’s add the __autoload() method now and take a look:

$db = new DB();
function __autoload($className) {
 echo $className;
 exit();
}

According to the description of the automatic loading mechanism above, it will output: Db, which is the class name of the class we need new. Therefore, at this time we can load the class library file as needed in the __autoload() method.

2. spl_autoload_register automatically loads

If it is a small project, you can use __autoload() to achieve basic automatic loading. But if a project is large, or different automatic loading is required to load files with different paths, __autoload will be useless at this time, because only one __autoload() function is allowed in a project, because PHP does not allow functions with duplicate names. , which means you cannot declare two __autoload() function files, otherwise a fatal error will be reported. then what should we do? Don’t worry, whatever you think of, the PHP master has already thought of it. So another awesome function like spl_autoload_register() was born and replaced it. It performs more efficiently and is more flexible.

Let’s first see how to use it, and add the following code to index.php.

<?php 
spl_autoload_register(function($className){
 if (is_file(&#39;./Lib/&#39; . $className . &#39;.php&#39;)) {
 require &#39;./Lib/&#39; . $className . &#39;.php&#39;;
 }
});
$db = new Db();
$db::test();

Add the following code to the Lib\Db.php file:

<?php 
class Db
{
 public static function test()
 {
 echo &#39;Test&#39;;
 }
}

After running index.php, when calling new Db(), spl_autoload_register will automatically go to the lib/ directory to find the corresponding Db.php file, and can execute $db::test(); after success. Similarly, if there are multiple php class files in the Lib\ directory, they can be called directly in index.php without requiring multiple files.

In other words, spl_autoload_register can be reused multiple times. This solves the shortcomings of __autoload. If a page has multiple spl_autoload_registers, the order of execution is in the order of registration, one by one. Look down and stop if you find it.

3. spl_autoload_register automatic loading and namespace namespace

For very complex systems, the directory structure will also be very complex, standard naming Space solves the problem of a large number of files, functions, and classes with duplicate names under complex paths. Autoloading is now the cornerstone of modern PHP frameworks, and spl_autoload_register is basically used to implement automatic loading. So spl_autoload_register namespace has become mainstream.

According to the PSR series of specifications, namespace naming has been very standardized, so the detailed path can be found based on the namespace to find the class file.

We use the simplest example to illustrate how complex systems automatically load class files.

First, we prepare the system directory structure:

----/Lib  // 类目录
 --Db.php
 --Say.php
----autoload.php // 自动加载函数
----index.php // 首页

The above is a basic system directory. What we want to achieve is to use namespace and automatic loading to call Lib directly on the homepage index.php Multiple classes in the directory.

We prepare two column files:

Db.php

<?php 
namespace Lib;
class Db
{
 public function __construct()
 {
 //echo &#39;Hello Db&#39;;
 }
 public static function test()
 {
 echo &#39;Test&#39;;
 }
}
Say.php
<?php
namespace Lib;
class Say 
{
 public function __construct()
 {
 //echo &#39;Hello&#39;;
 }
 public function hello()
 {
 echo &#39;say hello&#39;;
 }
}

以上两个普通的类文件,添加了命名空间: namespace Lib; 表示该类文件属于Lib\目录名称下的,当然你可以随便取个不一样的名字来表示你的项目名称。

现在我们来看autoload.php:

<?php 
spl_autoload_register(function ($class) {
 $prefix = &#39;Lib\\&#39;;
 $base_dir = __DIR__ . &#39;/Lib/&#39;;
 // does the class use the namespace prefix?
 $len = strlen($prefix);
 if (strncmp($prefix, $class, $len) !== 0) {
 // no, move to the next registered autoloader
 return;
 }
 $relative_class = substr($class, $len);
 // 兼容Linux文件找。Windows 下(/ 和 \)是通用的
 $file = $base_dir . str_replace(&#39;\\&#39;, &#39;/&#39;, $relative_class) . &#39;.php&#39;;
 if (file_exists($file)) {
 require $file;
 }
});

以上代码使用函数 spl_autoload_register() 首先判断是否使用了命名空间,然后验证要调用的类文件是否存在,如果存在就 require 类文件。

好了,现在我们在首页index.php这样调用:

<?php 
use Lib\Db;
use Lib\Say;
require &#39;./autoload.php&#39;;
$db = new Db();
$db::test();
$say = new Say;
$say->hello();

我们只需使用一个require将autoload.php加载进来,使用 use 关键字将类文件路径变成绝对路径了,当然你也可以在调用类的时候把路径都写上,如: new Lib\Db(); ,但是涉及到多个类互相调用的时候就会很棘手,所以我们还是在文件开头就使用 use 把路径处理好。

接下来就直接调用Lib/目录下的各种类文件了,你可以在Lib/目录下放置多个类文件尝试下。

运行index.php看看是不是如您所愿。

结束语

该文简单介绍了自动加载以及命名空间的使用,实际开发中,我们很少去关注autoload自动加载的问题,因为大多数现代PHP框架都已经处理好了文件自动加载的问题。开发者只需关注业务代码,使用规范的命名空间就可以了。当然,如果你想自己开发个项目不依赖大型框架亦或者自己开发php框架,那你就得熟悉下autoload自动加载这个好东西了,毕竟它可以让我们“偷懒”,省事多了。

现代php里,我们经常使用 Composer 方式安装的组件,都可以通过autoload实现自动加载,所以还是一个“懒”字给我们带来了极好的开发效率。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

有关JsonObject中的key-value数据解析排序(详细教程)

在Thinkjs3中如何使用静态资源目录

如何实现单层json按照key字母顺序排序(详细教程)

The above is the detailed content of Detailed interpretation of PHP automatic loading autoload and namespace. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool