Home >Backend Development >PHP Tutorial >PHP automatic loading class usage example analysis, PHP loading example analysis_PHP tutorial
The examples in this article describe the usage of PHP auto-loading class. Share it with everyone for your reference, the details are as follows:
<?php //function __autoload($class_name) { // require_once $class_name . '.php'; //} spl_autoload_register(array("core",'autoload'));//当实例化类的时候,自动调用core类中的autoload()方法来载入类 //也可以使用__autoload()来实现,但是php新版本建议使用spl_autoload_register,因为__autoload()会被逐渐废弃掉 $obj = new MyClass1(); $obj2 = new MyClass2(); class core { public static function autoload($class) { require $class.'.php'; } }
Understanding thoughts is the key:
Auto-loading objects
Many developers when writing object-oriented applications create a PHP source file for each class definition. A big annoyance is having to write a long list of include files (one file per class) at the beginning of each script.
In PHP 5, this is no longer necessary. You can define an __autoload() function that is automatically called when trying to use a class that has not yet been defined. By calling this function, the scripting engine has a last chance to load the required classes before PHP fails with an error.
Tip
spl_autoload_register() provides a more flexible way to implement automatic loading of classes. Therefore, use of the __autoload() function is no longer recommended and may be deprecated in a future version.
Readers who are interested in more PHP-related content can check out the special topics of this site: "Introduction Tutorial on PHP Object-Oriented Programming", "Summary of PHP Mathematical Operation Skills", "Summary of PHP Office Document Operation Skills (including word, excel, access, ppt)", "Complete PHP Array (Array) Operation Skills", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "php Regular Expression Usage Summary", and "php Common Database Operation Skills" Summary》
I hope this article will be helpful to everyone in PHP programming.