未定义的变量错误,尽管变量存在于已包含的文件中
Undefined variable error although the variable IS present in an already included file
我有一个名为 constants.php
的 PHP 脚本
constants.php:-
<?php
$projectRoot = "path/to/project/folder";
...
?>
然后我有另一个名为 lib.php
的文件
lib.php:-
<?php
class Utils {
function doSomething() {
...
// Here we do some processing where we need the $projectRoot variable.
$a = $projectRoot; //////HERE, I GET THE ERROR MENTIONED BELOW.
...
}
}
?>
然后我有另一个名为 index.php 的文件,其中包含上述两个文件。
index.php:-
<?php
...
require_once "constants.php";
...
require_once "lib.php";
(new Utils())->doSomething();
...
?>
现在,问题是当我 运行 index.php 时,我得到以下错误:
注意:未定义变量:第 19 行 /var/www/html/test/lib.php 中的 projectRootPath
我的问题是,为什么会出现此错误,我该如何解决?
显然,它与范围有关,但我已经阅读了 include
和 require
简单的复制并将包含的代码粘贴到包含它的脚本中。所以我很困惑。
因为,您正在访问函数范围内的变量。
函数外部的变量在函数内部不可访问。
您需要将它们作为参数传递,或者您需要添加关键字 global
才能访问它。
function doSomething() {
global $projectRoot;
...
// Here we do some processing where we need the $projectRoot variable.
$a = $projectRoot;
根据@RiggsFolly
:
作为参数传递
require_once "lib.php";
(new Utils())->doSomething($projectRoot);
...
<?php
class Utils {
function doSomething($projectRoot) {
...
// Here we do some processing where we need the $projectRoot variable.
$a = $projectRoot; //////HERE, I GET THE ERROR MENTIONED BELOW.
...
}
}
?>
我有一个名为 constants.php
的 PHP 脚本constants.php:-
<?php
$projectRoot = "path/to/project/folder";
...
?>
然后我有另一个名为 lib.php
的文件lib.php:-
<?php
class Utils {
function doSomething() {
...
// Here we do some processing where we need the $projectRoot variable.
$a = $projectRoot; //////HERE, I GET THE ERROR MENTIONED BELOW.
...
}
}
?>
然后我有另一个名为 index.php 的文件,其中包含上述两个文件。
index.php:-
<?php
...
require_once "constants.php";
...
require_once "lib.php";
(new Utils())->doSomething();
...
?>
现在,问题是当我 运行 index.php 时,我得到以下错误:
注意:未定义变量:第 19 行 /var/www/html/test/lib.php 中的 projectRootPath
我的问题是,为什么会出现此错误,我该如何解决?
显然,它与范围有关,但我已经阅读了 include
和 require
简单的复制并将包含的代码粘贴到包含它的脚本中。所以我很困惑。
因为,您正在访问函数范围内的变量。
函数外部的变量在函数内部不可访问。
您需要将它们作为参数传递,或者您需要添加关键字 global
才能访问它。
function doSomething() {
global $projectRoot;
...
// Here we do some processing where we need the $projectRoot variable.
$a = $projectRoot;
根据@RiggsFolly
:
作为参数传递
require_once "lib.php";
(new Utils())->doSomething($projectRoot);
...
<?php
class Utils {
function doSomething($projectRoot) {
...
// Here we do some processing where we need the $projectRoot variable.
$a = $projectRoot; //////HERE, I GET THE ERROR MENTIONED BELOW.
...
}
}
?>