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;
  • }
  • }
相關文章
相關標籤/搜索