替换PHP的__autoload函数?

栏目: PHP · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/2630549/replacement-for-phps-autoload-function

我已经阅读了如下所示在需要时动态加载类文件:

function __autoload($className)
{
   include("classes/$className.class.php");
}

$obj = new DB();

当你创建该类的一个新实例时,它会自动加载DB.class.php,但我也读过几篇文章说使用它是不好的,因为它是一个全局函数和你带入项目的任何库一个__autoload()函数会弄乱它.

那么有人知道解决方案吗?也许另一种方法可以达到与__autoload()相同的效果?在找到合适的解决方案之前,我将继续使用__autoload(),因为它不会开始成为一个问题,直到您引入库等.

谢谢.

我已经使用以下代码来使用spl_autoload_register,如果它不存在它会降级,并且还处理使用__autoload的库,你需要包含它.

//check to see if there is an existing __autoload function from another library
if(!function_exists('__autoload')) {
    if(function_exists('spl_autoload_register')) {
        //we have SPL, so register the autoload function
        spl_autoload_register('my_autoload_function');      
    } else {
        //if there isn't, we don't need to worry about using the stack,
        //we can just register our own autoloader
        function __autoload($class_name) {
            my_autoload_function($class_name);
        }
    }

} else {
    //ok, so there is an existing __autoload function, we need to use a stack
    //if SPL is installed, we can use spl_autoload_register,
    //if there isn't, then we can't do anything about it, and
    //will have to die
    if(function_exists('spl_autoload_register')) {
        //we have SPL, so register both the
        //original __autoload from the external app,
        //because the original will get overwritten by the stack,
        //plus our own
        spl_autoload_register('__autoload');
        spl_autoload_register('my_autoload_function');      
    } else {
        exit;
    }

}

因此,该代码将检查现有的__autoload函数,并将其添加到堆栈以及您自己的函数(因为spl_autoload_register将禁用正常的__autoload行为).

翻译自:https://stackoverflow.com/questions/2630549/replacement-for-phps-autoload-function


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

游戏编程权威指南

游戏编程权威指南

Mike McShaffry 麦克沙福瑞、David “Rez” Graham 格雷海姆 / 师蓉、李静、李青翠 / 人民邮电 / 2016-3 / 99.00元

全书分为4个部分共24章。首部分是游戏编程基础,主要介绍了游戏编程的定义、游戏架构等基础知识。 第二部分是让游戏跑起来,主要介绍了初始化和关闭代码、主循环、游戏主题和用户界面等。 第三部分是核心游戏技术,主要介绍了一些*为复杂的代码 示例,如3D编程、游戏音频、物理和AI编程等。 第四部分是综合应用,主要介绍了网络编程、多道程序设计和用C#创建工具等,并利用前面所讲的 知识开发出......一起来看看 《游戏编程权威指南》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具