在有的框架中的自動加載機制,在發現無法加載時, 直接報錯, 而沒有把控制權轉交給下一個自動加載方法., 如我要引入阿里云日志服務接口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 解決項目中多個自動加載沖突問題的詳細內容,更多請關注億速云其它相關文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。