代码之家  ›  专栏  ›  技术社区  ›  Daniel

PHP/Zend抱怨变量未定义

  •  0
  • Daniel  · 技术社区  · 17 年前

    情况:

    index.php:

    <?php
        include("foo.php");
        include("baz.php");
            foo("bar.php");
    ?>
    

    <?php
        $x = 42;
    ?>
    

    <?php
        function foo($p) {
            include_once($p); // please dont mind the inclusion hole
        }
    ?>
    

    bar.php:

    <?php
        echo $x;
    ?>
    

    放置全球x美元;在bar.php中删除了通知,但我理解为什么首先会有关于此的通知。。不包括像包含C头文件那样的工作吗?这意味着解释后的代码看起来像这样:

    <?php
        function foo($p) {
            include_once($p); // please dont mind the inclusion hole
        }
        $x = 42;
    
        // this however, is included by a function...
        // does the function's scope influence the stuff it includes?
        echo $x; // undefined variable
    ?>
    

    我的编辑器是Eclipse/Zend包。

    4 回复  |  直到 15 年前
        1
  •  3
  •   Dave Archer    17 年前

        2
  •  0
  •   Ivar    17 年前

        3
  •  0
  •   Dutow    17 年前

    即使变量和函数在同一个文件中,它也不起作用。

      1 <?php
      2
      3 $x = 3;
      4
      5 function t()
      6 {
      7   echo $x;
      8 }
      9
     10 t();
    

    但添加一个全球

      1 <?php
      2
      3 $x = 3;
      4
      5 function t()
      6 {
      7   global $x;
      8   echo $x;
      9 }
     10
     11 t();
    

    你可以看到“3”。

    在函数中,除非你声明它,否则你看不到全局变量。

        4
  •  0
  •   Galen    17 年前

    如果你更换

    foo("bar.php");
    

    随着

    include("bar.php");
    

    你会看到一切都很好,因为它把它放在当前范围内,而不是函数范围内