[phpstudy]PHP autoload实现自动加载类

更新时间:2017-12-13    来源:php常用代码    手机版     字体:

【www.bbyears.com--php常用代码】

下面是使用autoload机制加载Person类的例子:

 代码如下

/* autoload.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差不多。

 代码如下

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.bbyears.com/jiaocheng/37740.html

热门标签

更多>>

本类排行