Home > Backend Development > PHP Tutorial > php中使用__autoload()自动加载未定义类的实现代码_PHP

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

WBOY
Release: 2016-06-01 12:08:36
Original
776 people have browsed it

下面是一段使用__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),这样做即可以有效管理库文件,又解决了跨平台的问题。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template