Home Backend Development PHP Tutorial Detailed explanation of examples of PHP class automatic loading mechanism

Detailed explanation of examples of PHP class automatic loading mechanism

Jul 01, 2017 am 09:18 AM
php Example Detailed explanation

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 &#39;autload class:&#39;, $class_name, &#39;<br />&#39;;
}

new Demo();
Copy after login

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

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 &#39;autload class:&#39;, $class_name, &#39;<br />&#39;;
}
function classLoader($class_name) {
    echo &#39;SPL load class:&#39;, $class_name, &#39;<br />&#39;;
}
spl_autoload_register(&#39;classLoader&#39;);
new Test();//结果:SPL load class:Test
Copy after login

语法: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(&#39;CalssLoader::loader&#39;);    
$test = new Test();
Copy after login

一旦调用spl_autoload_register()函数,当调用未定义类时,系统会按顺序调用注册到spl_autoload_register()函数的所有函数,而不是自动调用autoload()函数。如果要避免这种情况,需采用一种更加安全的spl_autoload_register()函数的初始化调用方法:

if(false === spl_autoload_functions()){    
    if(function_exists(&#39;autoload&#39;)){    
        spl_autoload_registe(&#39;autoload&#39;,false);    
    }    
 }
Copy after login

spl_autoload_functions()函数会返回已注册函数的一个数组,如果SPL自动加载栈还没有被初始化,它会返回布尔值false。然后,检查是否有一个名为autoload()的函数存在,如果存在,可以将它注册为自动加载栈中的第一个函数,从而保留它的功能。之后,可以继续注册自动加载函数。

还可以调用spl_autoload_register()函数以注册一个回调函数,而不是为函数提供一个字符串名称。如提供一个如array('class','method')这样的数组,使得可以使用某个对象的方法。

下一步,通过调用spl_autoload_call('className')函数,可以手动调用加载器,而不用尝试去使用那个类。这个函数可以和函数class_exists('className',false)组合在一起使用以尝试去加载一个类,并且在所有的自动加载器都不能找到那个类的情况下失败。

f(spl_autoload_call(&#39;className&#39;) && class_exists(&#39;className&#39;,false)){    
  
    } else {    
    }
Copy after login

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!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles