温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php如何解决项目中多个自动加载冲突?

发布时间:2020-05-22 17:33:18 来源:亿速云 阅读:198 作者:鸽子 栏目:编程语言

在有的框架中的自动加载机制,在发现无法加载时, 直接报错, 而没有把控制权转交给下一个自动加载方法., 如我要引入阿里云日志服务接口sdk,该sdk中自带自动加载方法,如下:

<?php
/**
 * Copyright (C) Alibaba Cloud Computing
 * All rights reserved
 */
$version = '0.6.0';
function Aliyun_Log_PHP_Client_Autoload($className) {
    $classPath = explode('_', $className);
    if ($classPath[0] == 'Aliyun') {
        if(count($classPath)>4)
            $classPath = array_slice($classPath, 0, 4);
        $filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php';
        if (file_exists($filePath))
            require_once($filePath);
    }
}
spl_autoload_register('Aliyun_Log_PHP_Client_Autoload');

上面自动加载方法会与原有框架自己的加载方法冲突,解决方法如下:

<?php
function autoloadAdjust()
{
    // 取原有的加载方法
    $oldFunctions = spl_autoload_functions();
    // 逐个卸载
    if ($oldFunctions){
        foreach ($oldFunctions as $f) {
            spl_autoload_unregister($f);
        }
    }
    // 注册本框架的自动载入
    spl_autoload_register(
        # 就是aliyun sdk的加载方法
        function ($className) {
            $classPath = explode('_', $className);
            if ($classPath[0] == 'Aliyun') {
                    if(count($classPath)>4)
                    $classPath = array_slice($classPath, 0, 4);
                unset($classPath[0]);
                $filePath = dirname(__FILE__) . '/' . implode('/', $classPath) . '.php';
                if (file_exists($filePath))
                    require_once($filePath);
            }
        }
    );
    // 如果引用本框架的其它框架已经定义了__autoload,要保持其使用
    if (function_exists('__autoload')) {
        spl_autoload_register('__autoload');
    }
    // 再将原来的自动加载函数放回去
    if ($oldFunctions){
        foreach ($oldFunctions as $f) {
            spl_autoload_register($f);
        }
    }
}
# 最后调用上面方法
autoloadAdjust();

以上就是php 解决项目中多个自动加载冲突问题的详细内容,更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI