首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP include/require 系列差異全解析:性能、錯誤行為、最佳實踐

     編輯:PHP 綜合知識

四函數對比表

函數找不到文件語法錯誤重複包含返回值典型用途
includeWarning + 繼續Warning + 繼續每次執行1/false模板、可選配置
include_onceWarning + 繼續Warning + 繼續只執行一次1/false函數庫、類定義
requireFatal Error 停止Fatal Error 停止每次執行1/不返回核心依賴、初始化
require_onceFatal Error 停止Fatal Error 停止只執行一次1/不返回核心類庫、單例註冊

性能考量

  • _once 版本需維護已包含文件表(EG(included_files)),極微量開銷,可忽略。
  • OpCache 啟用後,編譯結果緩存,二次包含幾乎零成本。
  • 條件包含:if ($cond) include 'a.php'; 只能用 include,require 編譯期必須存在。

最佳實踐

  1. **類/介面/函數定義**:require_once(核心)或 Composer 自動加載(現代標準)。
  2. **配置文件**:require_once(缺失即致命)。
  3. **視圖模板**:include(允許不存在時降級)。
  4. **動態路由加載**:include 配合 file_exists 判斷。
  5. **廢棄 include/require 變量傳遞**:改用函數參數、返回值、依賴注入。

自動加載替代方案

<?php
// Composer PSR-4
require __DIR__.'/vendor/autoload.php';

// 手動最小實現
spl_autoload_register(function($class) {
    $file = __DIR__.'/src/'.str_replace('\\','/',$class).'.php';
    if (file_exists($file)) require $file;
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved