


Detailed explanation of examples of PHP class automatic loading mechanism
PHP’s Class automatic loadingMechanism
In the PHP development process, if you want to introduce it from the outside A class usually uses the include and require methods to include the file that defines the class. When this is developed on a small scale, there is no big problem. However, in large-scale development projects, doing so will generate a large number of require or include method calls, which not only reduces efficiency, but also makes the code difficult to maintain, and require_once is very costly.
Before PHP5, if each PHP framework wanted to implement automatic loading of classes, they usually implemented a traversal of directories according to a certain agreement, automatically A class or function that loads all files that match the agreed rules. Of course, the object-oriented support before PHP5 was not very good, and the use of classes was not as frequent as it is now. After PHP5, when loading a PHP class, if the file where the class is located is not included, or the class name is wrong, the Zend engine will automatically call the autoload function. This function requires users to implement the autoload function themselves. After PHP5.1.2 version, you can use the spl_autoload_register function to customize the automatic loading processing function. When this function is not called, SPL's custom spl_autoload function will be used by default.
1. Autoload example:
function autoload($class_name) { echo 'autload class:', $class_name, '<br />'; } new Demo();
The above code will output at the end: autoload class:Demo.
And then the error message is displayed: Fatal error: Class 'Demo' not found
We generally use _autoload to automatically load the class as follows:
<?php function autoload($class_name) { require_once ($class_name . “class.php”); } $memo= new Demo();
We can It can be seen that _autoload has to do at least three things. The first thing is to determine the class file name based on the class name. The second thing is to determine the disk path where the class file is located (in our example, it is the simplest case. The class and call Their PHP program files are in the same folder), and the third thing is to load the class from the disk file into the system. The third step is the simplest, just use include/require. To realize the functions of the first and second steps, the mapping method between the class name and the disk file must be agreed upon during development. Only in this way can we find its corresponding disk file based on the class name.
Therefore, when there are a large number of class files to be included, we only need to determine the corresponding rules, and then in the autoload() function, match the class name with the actual disk file to achieve lazy loading Effect. From here we can also see that the most important thing in the implementation of the autoload() function is the implementation of the mapping rules between the class name and the actual disk file.
But now comes the problem. If in the implementation of a system, if many other class libraries need to be used, these class libraries may be developed by different development engineers, and their class names are different from the actual disk files. Mapping rules vary. At this time, if you want to implement automatic loading of class library files, you must implement all mapping rules in the autoload() function. Therefore, the autoload() function may be very complicated or even impossible to implement. In the end, the autoload() function may become very bloated. Even if it can be implemented, it will have a great negative impact on future maintenance and system efficiency. In this case, introduced the SPL standard library in PHP5, a new solution, the spl_autoload_register() function.
2. spl_autoload_register() function
The function of this function is to register the function into the SPL autoload function stack and remove the system default autoload ()function. This can be seen in the following example:
function autoload($class_name) { echo 'autload class:', $class_name, '<br />'; } function classLoader($class_name) { echo 'SPL load class:', $class_name, '<br />'; } spl_autoload_register('classLoader'); new Test();//结果:SPL load class:Test
语法:bool spl_autoload_register ( [callback $autoload_function] ) 接受两个参数:一个是添加到自动加载栈的函数,另外一个是加载器不能找到这个类时是否抛出异常的标志。第一个参数是可选的,并且默认指向spl_autoload()函数,这个函数会自动在路径中查找具有小写类名和.php扩展或者.ini扩展名,或者任何注册到spl_autoload_extensions()函数中的其它扩展名的文件。
<?php class CalssLoader { public static function loader($classname) { $class_file = strtolower($classname).".php"; if (file_exists($class_file)){ require_once($class_file); } } } // 方法为静态方法 spl_autoload_register('CalssLoader::loader'); $test = new Test();
一旦调用spl_autoload_register()函数,当调用未定义类时,系统会按顺序调用注册到spl_autoload_register()函数的所有函数,而不是自动调用autoload()函数。如果要避免这种情况,需采用一种更加安全的spl_autoload_register()函数的初始化调用方法:
if(false === spl_autoload_functions()){ if(function_exists('autoload')){ spl_autoload_registe('autoload',false); } }
spl_autoload_functions()函数会返回已注册函数的一个数组,如果SPL自动加载栈还没有被初始化,它会返回布尔值false。然后,检查是否有一个名为autoload()的函数存在,如果存在,可以将它注册为自动加载栈中的第一个函数,从而保留它的功能。之后,可以继续注册自动加载函数。
还可以调用spl_autoload_register()函数以注册一个回调函数,而不是为函数提供一个字符串名称。如提供一个如array('class','method')这样的数组,使得可以使用某个对象的方法。
下一步,通过调用spl_autoload_call('className')函数,可以手动调用加载器,而不用尝试去使用那个类。这个函数可以和函数class_exists('className',false)组合在一起使用以尝试去加载一个类,并且在所有的自动加载器都不能找到那个类的情况下失败。
f(spl_autoload_call('className') && class_exists('className',false)){ } else { }
SPL自动加载功能是由spl_autoload() ,spl_autoload_register(), spl_autoload_functions() ,spl_autoload_extensions()和spl_autoload_call()函数提供的。
The above is the detailed content of Detailed explanation of examples of PHP class automatic loading mechanism. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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,

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

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

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 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.
