PHP Conference Japan 2024

require

(PHP 4, PHP 5, PHP 7, PHP 8)

requireinclude 完全相同,差別在於失敗時會產生嚴重的 E_COMPILE_ERROR 等級錯誤。換句話說,它會停止執行腳本,而 include 只會發出警告 (E_WARNING),讓腳本可以繼續執行。

請參閱 include 文件以了解其運作方式。

新增註解

使用者貢獻的註解 3 則註解

chris at chrisstockton dot org
17 年前
請記住,當使用 require 時,它是一個陳述式,而不是函式。沒有必要寫成
<?php
require('somefile.php');
?>

以下方式
<?php
require 'somefile.php';
?>

是較佳的,這可以避免你的同事找你麻煩,以及關於 require 真正是什麼的瑣碎對話。
Marcel Baur
3 年前
如果你的引入檔案回傳值,你可以從 require() 取得結果,例如:

foo.php
<?php
return "foo";
?>

$bar = require("foo.php");
echo $bar; // 等於 "foo"
jave dot web at seznam dot cz
10 個月前
永遠使用 __DIR__ 來定義相對於目前 __FILE__ 的路徑。
(或另一個原始基於 __DIR__/__FILE__ 的設定)

try & catch - 不要被「致命的 E_COMPILE_ERROR」這些字眼搞混 - 它仍然只是一個實作 Throwable 的內部 Error - 它可以被捕獲

<?php
try {
require(
__DIR__ . '/something_that_does_not_exist');
} catch (
\Throwable $e) {
echo
"This was caught: " . $e->getMessage();
}
echo
" End of script.";
?>

請注意,這仍然會發出警告「Failed to open stream: No such file or directory...」,除非你在 require 前面加上「@」符號,這點我強烈建議不要,因為這會忽略/壓制任何診斷錯誤(除非你已指定 set_error_handler())。但即使你在 require 前面加上「@」符號,它仍然會被捕獲。
To Top