Home  >  Article  >  Backend Development  >  Use __autoload() in php to automatically load undefined classes

Use __autoload() in php to automatically load undefined classes

WBOY
WBOYOriginal
2016-07-25 09:05:451080browse
  1. /**
  2. * Automatically load related class library files
  3. */
  4. function __autoload($classname){
  5. if(substr($classname,-6)=="Action"){
  6. include APP_PATH.'controllers /'.$classname.'.class.php';
  7. }elseif(substr($classname, -5)=="Model"){
  8. include APP_PATH.'models/'.$classname.'.class.php' ;
  9. }elseif($classname=="Smarty"){
  10. include SYSTEM_PATH.'smarty/Smarty.class.php';
  11. }else{
  12. include APP_PATH.'common/'.$classname.'.class.php' ;
  13. }
  14. }
  15. ?>
Copy code

Another way to include the path:

  1. function __autoload($class_name) {
  2. $path = str_replace('_', DIRECTORY_SEPARATOR, $class_name);
  3. require_once $path.'.php';
  4. }
  5. ?>
Copy code

Instructions: Convert the underscore to the directory separator (DIRECTORY_SEPARATOR). This can effectively manage library files and solve cross-platform problems.



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