


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!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
