When writing code, we often encounter a headache problem, which is to introduce many classes into a page, and we need to use the include_once or require_once() function to introduce them one by one. When the imported content is not much, it is still acceptable, but if there are a dozen or dozens of files that need to be imported, the number of operations will be large, not to mention irritating, and there will be cases of repeated introduction or forgetting to cite.
Now in PHP5 we can use the __autoload() method to solve this problem. The __autoload() method can automatically instantiate the classes that need to be used. When a program uses a class but the class has not been instantiated, PHP5 will call the __autoload() method to automatically search for files with the same name as the class in the specified path. If found, the program continues execution; otherwise, an error is reported.
Note:
All other methods must be added inside the class to work. __autoload() is the only method that is not added in the class
As long as it is added inside the class When a class is used in the page, the class name will be automatically passed to this parameter.
For example:
The code of the class file sport.class.php:
<?php class Sport{ private $type; public function __construct($type){ $this->type = $type; } public function __toString(){ return $this->type; } } ?>
The code under the index.php file:
<?php function __autoload($class_name){ //创建__autoload方法 $class_path = $class_name . '.class.php'; //类文件路径 if(file_exists($class_path)){ //判断文件是否存在 include_once($class_path); //动态引入文件 }else echo '类路径错误'; } $sport = new Sport('打篮球'); echo $sport; ?>
First Common classes are found in the class file sport.class.php, but do not instantiate them. Then introduce the classes in the class file into the php file index.php.
The above is the detailed content of Detailed explanation of magic method __autoload() instance (php advanced object-oriented tutorial). For more information, please follow other related articles on the PHP Chinese website!