Home > php教程 > php手册 > php中使用__autoload()自动加载未定义类的实现代码

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

WBOY
Release: 2016-06-06 20:32:12
Original
1209 people have browsed it

当PHP引擎遇到未实例化的类时就会触发这个方法,当然你的php代码中要用到__autoload()才可以哦

下面是一段使用__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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template