Home  >  Article  >  Backend Development  >  php中使用__autoload()自动加载未定义类的实现代码_php技巧

php中使用__autoload()自动加载未定义类的实现代码_php技巧

WBOY
WBOYOriginal
2016-05-17 09:06:47850browse

下面是一段使用__autoload()的代码,供大家学习参考:

复制代码 代码如下:

/**
* 自动加载相关类库文件
*/
function __autoload($classname){
if(substr($classname,-6)=="Action"){
include APP_PATH.'controllers/'.$classname.'.class.php';
}elseif(substr($classname, -5)=="Model"){
include APP_PATH.'models/'.$classname.'.class.php';
}elseif($classname=="Smarty"){
include SYSTEM_PATH.'smarty/Smarty.class.php';
}else{
include APP_PATH.'common/'.$classname.'.class.php';
}
}
?>

另一种包含路径的方法:

复制代码 代码如下:

function __autoload($class_name) {
$path = str_replace('_', DIRECTORY_SEPARATOR, $class_name);
require_once $path.'.php';
}
?>


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