未定义的变量错误,尽管变量IS存在于已包含的文件中[重复]

问题描述 投票:-1回答:1

我有一个名为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

我的问题是,为什么我会收到此错误,我该如何解决?

显然,它与范围有关,但我已经阅读了includerequire简单的复制并将包含的代码粘贴到包含它的脚本中。所以我很困惑。

php scope include require
1个回答
1
投票

因为,您正在访问函数范围中的变量。

函数外部的变量在函数内部不可访问。

您需要将它们作为参数传递,或者需要添加关键字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.
    ...
  }
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.