[英]Can PHP __autoload() a class from within another __autoload() of the same class?
[英]PHP autoload can't use another folder
我上課有問題。 我有3個文件夾,叫他們one
, two
和three
。 one
文件夾的功能類似於控制器, two
模型和three
視圖。 我已經在two
文件夾(模型層)中創建了autoload類,但是我不能調用另一個類。 我的autoload.php文件如下所示:
<?php
function __autoload($class){
include 'two/'.$class .'.php';
}
spl_autoload_register('__autoload');
如果我在index.php中調用autoload,那么在two
文件夾中看不到另一個,則無法從一個和三個文件夾中調用方法。 如何修復自動加載方法?
使用spl_autoload_register
可以注冊多個自動加載器。 但是第一種方法是注冊一個自動加載器,該自動加載器檢查其中一個文件夾( one
, two
或three
)中是否存在$class.php
並將其包括在內。
spl_autoload_register(function ($className) {
$folders = ['one', 'two', 'three'];
foreach ($folders as $folder) {
if (file_exists($path = $folder. '/'.$className .'.php')) {
include $path;
break;
}
}
});
但這也是一個有問題的方法。 如果你有一Foo
兩個階級one
和two
目錄? 您要導入哪個? 要解決這些沖突,可以使用名稱空間 ,並遵循PSR-0 / 4的指令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.