PHP autoload实现自动加载类
autoload机制可以使得PHP程序有可能在使用类时才自动包含类文件,而不是一开始就将所有的类文件include进来,这种机制也称为lazy loading。
下面是使用autoload机制加载Person类的例子,代码如下:
/* autoload.php */
<?php
function __autoload($classname) {
require_once ($classname . "class.php");
}
$person = new Person("Altair", 6);
var_dump($person);
?>PHP的autoload机制的实现,要在PHP中实现自动加载类,那就要说到一个魔术方法了,__autoload();这是PHP5添加的自动加载类方法,只要定义了该函数,那么如果PHP运行到该类找不到时,就会根据__autoload的规则去寻找。
自己也规划一下,跟set_include_path和get_include_path来配合使用,使自动加载类更完善点,代码飙一下(模仿magento的),代码如下:
$paths[] = BP . DS . 'app' . DS . 'local'; $paths[] = BP . DS . 'app' . DS . 'base'; $paths[] = BP . DS . 'lib'; $appPath = implode(PS, $paths); set_include_path($appPath . PS . get_include_path());
这样就可以为PHP添加默认的类加载环境,这里只是把路径添加到了PHP环境,如果还要继续添加规则,可以再定义__autoload函数,不过我这里是对象使用的,就换了一种方法:spl_autoload_register方法,下面是自己根据magento的规则,自己弄了一套,其实跟magento差不多,代码如下:
<?php
class Autoload {
/**
* 自身对象
*
*/
protected static $_instance = null;
public function __construct() {
}
/*
* 实例化自身
*
*/
public static function instance() {
if (null == self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
*
* 注册自动加载函数
*/
public static function register() {
spl_autoload_register(array(
self::instance() ,
'autoload'
));
}
/*
*
* 自动加载类
*/
public function autoload($class) {
if (!is_string($class)) {
return;
}
$classFile = str_replace(' ', DS, ucwords(str_replace('_', ' ', $class)));
$classFile.= '.php';
return include $classFile;
}
}
?>
文章链接:http://www.phprm.com/mxdx/fs1411.html
随便收藏,请保留本文地址!