Home > Article > Backend Development > Detailed explanation of how PHP uses _autoload to automatically load class instances
When using PHP's OO mode to develop a system, it is usually customary to store the implementation of each class in a separate file. This will make it easy to reuse the class and will also be convenient for future maintenance. . This is also one of the basic ideas of OO design
Before PHP5, if you need to use a class, you only need to include it directly using include/require
test.class.php
<?php class abc{ function construct() { echo 'www.hzhuti.com; } } ?>
load.php
The code is as follows
<?php class LOAD { static function loadClass($class_name) { $filename = $class_name.".class.php"; if (is_file($filename)) return include_once $filename; } } /** * 设置对象的自动载入 * spl_autoload_register — Register given function as autoload() implementation */ spl_autoload_register(array('LOAD', 'loadClass')); $a = new Test();//实现 自动加载 ,很多框架就用这种方法 自动加载类 ?>
autoload()
In actual projects, it is impossible to write all classes in one PHP file. When a PHP file needs to call a class declared in another file, this file needs to be introduced through include. However, sometimes, in projects with many files, it is necessary to include all required class files one by one. A big trouble is having to write a long include file## at the beginning of each class file. #list of. Can we import the php file where this class is located when we use it? To this end, PHP provides the autoload() method, which 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.
The autoload() method receives one parameter, which is the class name of the class to be loaded, so at this time, the class name needs to correspond to the file name, such as Person.php, and the corresponding class name is Pserson.
Look at a complete example below
class ClassA{ public function construct(){ echo “ClassA load success!”; } } //定义一个类ClassA,文件名为ClassA.php class ClassA{ public function construct(){ echo “ClassA load success!”; } } class ClassB extends ClassA { public function construct(){ //parent::construct(); echo “ClassB load success!”; } } //定义一个类ClassB,文件名为ClassB.php,ClassB继承ClassA class ClassB extends ClassA { public function construct(){ //parent::construct(); echo “ClassB load success!”; } }
After defining two classes for testing, let’s write a PHP running program file containing the autoload() method as follows:
function autoload($classname){ $classpath=”./”.$classname.'.php'; if(file_exists($classpath)){ require_once($classpath); } else{ echo ‘class file'.$classpath.'not found!'; } } $newobj = new ClassA(); $newobj = new ClassB();
The above is the detailed content of Detailed explanation of how PHP uses _autoload to automatically load class instances. For more information, please follow other related articles on the PHP Chinese website!