Heim  >  Artikel  >  Backend-Entwicklung  >  php中使用__autoload()自动加载未定义的类

php中使用__autoload()自动加载未定义的类

WBOY
WBOYOriginal
2016-07-25 09:05:451077Durchsuche
  1. /**
  2. * 自动加载相关类库文件
  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. ?>
复制代码

另一种包含路径的方法:

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

说明:将下划线转换为目录分隔符(DIRECTORY_SEPARATOR),这样做即可以有效管理库文件,又解决了跨平台的问题。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn