Home Backend Development PHP Tutorial Application summary of PHP automatic loading autoload and namespace

Application summary of PHP automatic loading autoload and namespace

Apr 19, 2018 pm 02:16 PM
autoload php

Let me first tell you what a namespace is.

"What is a namespace? Broadly speaking, a namespace is a way of encapsulating things. This abstract concept can be seen in many places. For example, in operating systems, directories are used to group related files. For directories For files, it plays the role of a namespace. For example, the file foo.txt can exist in the directories /home/greg and /home/other at the same time, but two foo.txt cannot exist in the same directory document. 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. The application of this principle to the field of programming is the concept of 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. 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 the class, it will automatically call the __autoload($class_name) method, our new class_name It becomes the parameter of this method. So we can use new in this method according to our needs Various judgments and divisions of class_name require the corresponding path class file to achieve automatic loading.

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

index.php

<?php 
$db = new Db();
Copy after login

If we do not manually import the Db class, the program may report an error saying that this class cannot be found:

Fatal error: Uncaught Error: Class 'DB' not found in D:webhellowebademo2017autoloadindex.php:2 Stack trace: #0 {main} thrown in D:webhellowebademo2017autoloadindex.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();
}
Copy after login

According to the description of the automatic loading mechanism above, the output will be: 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, use __autoload() Basic automatic loading can be achieved. 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 is allowed in a project. __autoload() function, because PHP does not allow functions with duplicate names, which means you cannot declare two __autoload() function file, 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 spl_autoload_register() In this way, another awesome function was born and replaced it. It performs more efficiently and is more flexible.

Let’s first see how to use it. 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();
Copy after login

Add the following code to the LibDb.php file:

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

After running index.php, when new Db() is called, spl_autoload_register It will automatically go to the lib/ directory to find the corresponding Db.php file. After success, $db::test(); can be executed. . 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. Then if a page has multiple spl_autoload_registers, the execution order is according to the order of registration. Look down one by one. If found Just stop.

3. spl_autoload_register automatic loading and namespace namespace

For very complex systems, the directory structure will also be very complex. The standardized namespace 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, basically spl_autoload_register to implement automatic loading. So spl_autoload_register namespace It became a 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 // 首页
Copy after login

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

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;;
 }
}
Copy after login

以上两个普通的类文件,添加了命名空间: 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;
 }
});
Copy after login

以上代码使用函数 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();
Copy after login

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

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

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

结束语

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

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


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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles