English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PHP Class/Object function reference manual
__autoload() function attempts to load undefined classes
__autoload ( string $class );
You can enable class auto-loading by defining this function.
class - Required. The name of the class to be loaded.
No return value.
The following examples illustrate the usage of __autoload, and the ClassA and ClassB classes are loaded from the ClassA.php and ClassB.php files respectively
<?php //Define a class ClassA, file name ClassA.php class ClassA{ public function __construct(){ echo 'ClassA load success!'; } } ?>
<?php //Define a class ClassB, file name ClassB.php, ClassB inherits ClassA class ClassB extends ClassA { public function __construct(){ echo 'ClassB load success!'; } } ?>
<?php function __autoload($classname) { $classpath="./".$classname.'.php'; if(file_exists($classpath)){ require_once($classpath); } else{ echo 'class file' . $classpath . 'not found!'; } } //When the ClassA class does not exist, the __autoload() function is automatically called with the parameter "ClassA" $obj = new ClassA(); //When the ClassB class does not exist, the __autoload() function is automatically called with the parameter "ClassB" $obj2 = new ClassB(); ?>
In PHP 5 In it, you can define a __autoload() function that will be automatically called when trying to use a class that has not been defined yet. By calling this function, the script engine has the last chance to load the required class before PHP fails. The parameter received by the __autoload() function is the name of the class you want to load. Therefore, when you are doing a project, you need to follow certain rules when organizing the filename of the class definition file, preferably centered around the class name, and you can also add a unified prefix or suffix to form the filename, such as xxx_classname.php, classname_xxx.php, and so on.