php專案中類的自動載入
主要函式:spl_autoload_register() — 註冊給定的函式作為 __autoload() 的實現
將函式註冊到SPL __autoload函式佇列中。如果該佇列中的函式尚未啟用,則啟用它們。
如果在你的程式中已經實現了__autoload()函式,它必須顯式註冊到__autoload()佇列中。因為spl_autoload_register()函式會將Zend Engine中的__autoload()函式取代為spl_autoload()或spl_autoload_call()。
如果需要多條 autoload 函式,spl_autoload_register() 滿足了此類需求。 它實際上建立了 autoload 函式的佇列,按定義時的順序逐個執行。相比之下, __autoload() 只可以定義一次。
<?php
// $class 類名
function autoloader_1($class) {
include 'classes/' . $class . '.class.php';
}
function autoloader_2($class) {
include 'classes/' . $class . '.class.php';
}
// 可以多次使用,但 __autoload() 函式只能使用一次。
spl_autoload_register('autoloader_1');
spl_autoload_register('autoloader_2');
// 或者,自 PHP 5.3.0 起可以使用一個匿名函式
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
php類的自動載入例項:
index.php檔案
<?php
define("BASEDIR", __DIR__);
include BASEDIR . "/app/Loader.php";
// 自動載入類及檔案
spl_autoload_register('\\app\\Loader::Autoload');
app目錄下的Loader.php檔案
<?php
namespace app;
class Loader
{
static function autoload( $class )
{
require BASEDIR . '/' . str_replace('\\', '/', $class) . '.php';
}
}
以上內容希望幫助到大家,更多PHP大廠PDF面試文件,PHP進階架構視訊資料,PHP精彩好文免費獲取可以關注公眾號:PHP開源社群,或者訪問:
「其他文章」
- 基於Nginx的負載均衡原理與實戰
- PHP控制反轉(IOC)和依賴注入(DI)
- 深入理解PHP7核心之Reference
- php中類的不定引數使用示例
- php單例模式的常見應用場景
- laravel 配置MySQL讀寫分離
- PHP的垃圾回收機制(建議收藏)
- 【shell指令碼】字串和陣列的使用
- PHP-FPM是什麼東東?
- PHP 編寫守護程序
- PHP命令列指令碼接收傳入引數的三種方式
- php專案中類的自動載入
- 複習下Linux去除重複項命令uniq
- 深入理解PHP核心:變數及資料型別
- Swoole協程與傳統fpm同步模式比較
- PHP中Session ID的實現原理
- 寫一手好SQL,該從哪裡入手最好?
- PHP命令列指令碼接收傳入引數的三種方式
- 使用 Shell 在多伺服器上批量操作
- PHP實現使用者異地登入提醒功能的方法