替代PHP的__autoload函数? [英] Replacement for PHP's __autoload function?

查看:79
本文介绍了替代PHP的__autoload函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读有关在需要时使用类似这样的函数动态加载类文件的信息:

I have read about dynamically loading your class files when needed in a function like this:

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

$obj = new DB();

当您创建该类的新实例时,哪个会自动加载DB.class.php,但是我也读了几篇文章,因为它是全局函数,因此带入项目的任何库都很难使用它有__autoload()函数会搞砸它.

Which will automatically load DB.class.php when you make a new instance of that class, but I also read in a few articles that it is bad to use this as it's a global function and any libraries that you bring into your project that have an __autoload() function will mess it up.

那么有人知道解决方案吗?也许获得与__autoload()相同效果的另一种方法?在找到合适的解决方案之前,我将继续使用__autoload(),因为在引入库之类的东西之前,它不会成为问题.

So does anyone know of a solution? Perhaps another way to achieve the same effect as __autoload()? Until I find a suitable solution I'll just carry on using __autoload() as it doesn't start becoming a problem until you bring in libraries and such.

谢谢.

推荐答案

我使用以下代码使用spl_autoload_register,如果不存在它会降级,并处理使用__autoload的库,需要包括.

I have used the following code to use spl_autoload_register in a way that it will degrade if it isn't present, and also handle libraries that use __autoload, that you need to include.

//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函数,并将其以及您自己的__autoload函数添加到堆栈中(因为spl_autoload_register将禁用常规的__autoload行为).

So, that code will check for an existing __autoload function, and add it to the stack as well as your own (because spl_autoload_register will disable the normal __autoload behaviour).

这篇关于替代PHP的__autoload函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆