php - 替代 PHP 的 __autoload 函数?

标签 php class libraries autoload

我读过有关在函数需要时动态加载类文件的内容,如下所示:

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 行为)。

关于php - 替代 PHP 的 __autoload 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2630549/

相关文章:

azure - 无法在 azure synapse Analytics Spark 池上上传工作区包和requirement.txt 文件

java - 如何在 NetBeans 中创建库

php - 尝试使用 PNG 和 JPEG 支持构建 PHP 和 GD

javascript - 使用 PHP、AJAX、Javascript 的 Cordova/Phonegap 登录无法正常工作

php - SQL LEFT JOIN & AND 关键字

eclipse - 如何使用 Eclipse 将类导入现有 Java 项目

php - 默认情况下在结帐页面上显示运输字段

Javascript - 添加类和样式先见之明

c++ - 在 Objective C 中添加 "->"

opencv - 如何在 ubuntu 18.04 中正确配置 g++ 与 opencv 的链接?