在函数内调用 "require"
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
的原因是每次深入文件夹结构时我都需要增加每个路径上的 ../
。我不想手动添加它们。
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
中,我会:
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");
在我正在处理的页面中,我做的第一件事是包含我的 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
.
req("template/head.php");
我使用自定义 require
的原因是每次深入文件夹结构时我都需要增加每个路径上的 ../
。我不想手动添加它们。
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
中,我会:
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");