Home  >  Article  >  Backend Development  >  Detailed explanation of magic method __autoload() instance (php advanced object-oriented tutorial)

Detailed explanation of magic method __autoload() instance (php advanced object-oriented tutorial)

巴扎黑
巴扎黑Original
2017-04-18 18:17:442187browse

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 . &#39;.class.php&#39;;                           //类文件路径
if(file_exists($class_path)){                                                  //判断文件是否存在
include_once($class_path);                                          //动态引入文件
}else
echo &#39;类路径错误&#39;;
}
$sport = new Sport(&#39;打篮球&#39;);
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn