PHPautoload实现自动加载类

机制可使得PHP程序有可能在使用类时才自动包含类文件,而不是一开始就将全部的类文件include进来,这种机制也称为lazy loading。
下面是使用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;
  • }
  • }
相关文章
相关标签/搜索