您好,欢迎访问一九零五行业门户网

PHP autoload实现自动加载类_PHP教程

autoload机制可以使得php程序有可能在使用类时才自动包含类文件,而不是一开始就将所有的类文件include进来,这种机制也称为lazy loading。
下面是使用autoload机制加载person类的例子:
 代码如下 复制代码
/* autoload.php */
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差不多。
 代码如下 复制代码
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.bkjia.com/phpjc/633080.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/633080.htmltecharticleautoload机制可以使得php程序有可能在使用类时才自动包含类文件,而不是一开始就将所有的类文件include进来,这种机制也称为lazy loading。 下...
其它类似信息

推荐信息