【问题标题】:Undefined variable error although the variable IS present in an already included file [duplicate]尽管变量存在于已包含的文件中,但未定义的变量错误[重复]
【发布时间】:2019-08-24 20:28:54
【问题描述】:

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

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

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

    您需要将它们作为参数传递,或者您需要添加关键字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.
        ...
      }
    }
    ?>
    

    【讨论】:

    • 哎呀!全球的??每次都在函数调用上传递值会更好
    • @RiggsFolly 为什么这样更好?
    • 因为您永远无法完全确定全局在任何一个时间点将包含什么。由于它可以从任何地方访问,任何东西都可能改变了它的值,这意味着当你进入函数时它不会是你期望的那样
    猜你喜欢
    • 2014-10-09
    • 2012-10-29
    • 2012-04-18
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多