This article mainly introduces PHP's reflection and automatic loading. It analyzes the principles of PHP loading and the implementation techniques of automatic loading with examples. I hope it will be helpful to everyone's understanding of PHP's reflection and automatic loading.
The example in this article describes how to implement lazy loading in PHP. Share it with everyone for your reference. The specific analysis is as follows:
Ordinary PHP loading is to load external files through include(), require() and other methods, and then call the method through the instance or directly call the static method, and it is really difficult to write the introduction statement in this way. Trouble, some frameworks will import all the files with a specific path, and they can be used by instantiating them directly. However, some class packages may not be used in this way. The more class packages you write, the more things you need to load. , affecting program performance.
You can directly obtain a reflection class of the corresponding class through PHP's reflection class ReflectionClass:
The test.php file is as follows:
<?php class test{ public function showName(){ var_dump(__CLASS__); } } ?>
index.php file is as follows:
##
<?php var_dump(get_included_files()); $rf = new ReflectionClass('test'); var_dump(get_included_files()); $testObj = $rf->newInstance(); $testObj->showName(); function __autoload($classname){ $classpath = './' . $classname . '.php'; if (file_exists($classpath)) { require_once($classpath); }else { echo 'class file'.$classpath.'not found!'; } } ?> //array // 0 => string 'D:\code\www\test\index.php'(length=26) //array // 0 => string 'D:\code\www\test\index.php'(length=26) // 1 => string 'D:\code\www\text\test.php'(length=25) //string 'test' (length=4)
var_dump(spl_autoload_functions()); spl_autoload_register('newAutoload'); var_dump(spl_autoload_functions()); $testObj1 = getInstance('test'); $testObj2 = getInstance('test'); $testObj3 = getInstance('test'); function getInstance($class, $returnInstance = false){ $rf = new ReflectionClass($class); if ($returnInstance) return $rf->newInstance(); } function newAutoload($classname){ $classpath = './' . $classname . '.php'; if (file_exists($classpath)) { var_dump('require success'); require_once($classpath); } else { echo 'class file ' . $classpath . ' not found!'; } } //array // 0 => string '__autoload' (length=10) //array // 0 => string 'newAutoload' (length=11) //string 'require success' (length=15)
Related recommendations:
PHP automatically loads objects (take MVC framework as an example)
php automatic loading function __autoload()
The above is the detailed content of PHP reflection and automatic loading. For more information, please follow other related articles on the PHP Chinese website!