[英]Calling “require” inside a function
在我正在處理的頁面中,我要做的第一件事是包括我的tools.php
文件。 說, index.php
require("../scripts/tools.php");
接下來,我創建一個自定義CSS
$custom_css = [
$link([
"rel" => "stylesheet",
"type" => "text/css",
"media" => "screen",
"href" => BASE . "css/layout-list.css",
]),
];
並使用在tools.php
聲明的自定義require函數包含head元素。
req("template/head.php");
我使用自定義require
的原因是因為每次我深入文件夾結構時,都需要增加每個路徑上的../
s。 我不想手動添加它們。
tools.php
有一個base()
函數,它會自動計算返回主文件夾所需的../
s並將其分配給BASE
常量。 該BASE
常量在req()
函數中使用
function req($path) {
require(BASE . $path);
}
這(種類)有效。 問題在於,由於(實際的)require是在函數內部調用的,因此head.php
無法訪問$custom_css
,而index.php
無法訪問head.php
內部的任何變量。
我想出的解決方案是在使用變量之前聲明該變量是全局變量。
因此,如果我必須從head.php
訪問index.php
$custom_css
, head.php
在head.php
我會這樣做:
global $custom_css;
if (!isset($custom_css)) {
$custom_css = [];
}
如果我必須從index.php
訪問head.php
的變量,則必須在head.php
全局聲明該變量:
global $head_var;
$head_var = 4;
這個過程似乎很累人並且多余。 有沒有辦法改變require
效果的地方? 即使文件包含在函數中,也要使包含的文件中的所有變量均為全局變量?
如果所有的自定義req
確實是在前面加上中定義的常量tools.php
,為什么不直接使用常數?
require(BASE."template/head.php");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.