• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP __autoload与spl_autoload

php 搞代码 3年前 (2022-01-23) 14次浏览 已收录 0个评论

__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..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 requ/本文来源gaodai#ma#com搞*!代#%^码网%搞代gaodaima码ire 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;            }        }    });

以上就介绍了PHP __autoload与spl_autoload,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP __autoload与spl_autoload

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址