PHP __autoload与spl_autoload

来源:互联网 发布:淘宝子账号可以开店吗 编辑:程序博客网 时间:2024/06/02 13:05
      __autoload的最大缺陷是无法有多个autoload方法。
      好了, 想想下面的这个情景,你的项目引用了别人的一个项目,你的项目中有一个__autoload,别人的项目也有一个__autoload,这样两个__autoload就冲突了。解决的办法就是修改__autoload成为一个,这无疑是非常繁琐的。 

      因此我们急需使用一个autoload调用堆栈,这样spl的autoload系列函数就出现了。你可以使用spl_autoload_register注册多个自定义的autoload函数。

      如果你的PHP版本大于5.1的话,你就可以使用spl_autoload。先了解spl的几个函数: 


spl_autoload 是_autoload()的默认实现,它会去include_path中寻找$class_name(.php/.inc) 


实际项目中,通常方法如下(当类找不到的时候才会被调用):

  // Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method.    // It auto-loads any file it finds starting with class.<classname>.php (LOWERCASE), eg: class.from.php, class.db.php    spl_autoload_register(function($class_name) {        // Define an array of directories in the order of their priority to iterate through.        $dirs = array(            'project/', // Project specific classes (+Core Overrides)            'classes/', // Core classes example            'tests/',   // Unit test classes, if using PHP-Unit        );        // Looping through each directory to load all the class files. It will only require a file once.        // If it finds the same class in a directory later on, IT WILL IGNORE IT! Because of that require once!        foreach( $dirs as $dir ) {            if (file_exists($dir.'class.'.strtolower($class_name).'.php')) {                require_once($dir.'class.'.strtolower($class_name).'.php');                return;            }        }    });


0 0
原创粉丝点击