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

Detailed explanation of examples of PHP class automatic loading mechanism

伊谢尔伦
伊谢尔伦Original
2017-07-01 09:18:551298browse

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();

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 &#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

语法: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();

      一旦调用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);    
    }    
 }

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 {    
    }

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