为什么我的$ setting数组变量没有保持其值?

And*_*nna -1 php zend-framework

我有以下问题: -

//index.php
<?php

define('PATH','Ajfit/');

/* Get all the required files and functions */
require(PATH . 'settings.inc.php');
require(PATH . 'inc/common.inc.php');

?>

//setting.inc.php
<?php
      $settings['language']='English';
?>

//inc/common.inc.php
<?php
      //global $settings, $lang, $_SESSION; //$setting = null????
      $language = $settings['language']; //$language is still null
?>
Run Code Online (Sandbox Code Playgroud)

当我尝试访问common.inc.php中的全局变量$ settings时,即使我在setting.inc.php中设置变量,它也会设置为null.如果我调试,当我退出setting.inc.php时,$ settings valiable在index.php中设置,但是当我进入common.inc.php时,$ settings valiable被设置为null.

有没有人有任何想法?

Jon*_*and 5

答:inc/common.inc.php文件中,您不需要使用global关键字,该变量已经可以访问.使用global重新定义变量,从而制作null.

说明:

变量范围是这里的关键.在global当范围变更的关键字时,才需要.常规文件(包括include()s)的范围都是相同的,因此所有变量都可以被同一范围内的任何php访问,即使它来自不同的文件.

您需要使用的示例global是在函数内部.函数的范围不同于普通php的class范围,它与范围不同,依此类推.

例:

//foo.php
  $foo = "bar";

  echo $foo; //prints "bar" since scope hasn't changed.

  function zoo() {
    echo $foo; //prints "" because of scope change.
  }

  function zoo2() {
    global $foo;
    echo $foo; //prints "bar" because $foo is recognized as in a higher scope.
  }

  include('bar.php');

//bar.php
  echo $foo; //prints "bar" because scope still hasn't changed.

  function zoo3() {
    echo $foo; //prints "" for the same reason as in zoo()
  }

  function zoo4() {
    global $foo;
    echo $foo; //prints "bar" for the same reason as in zoo2()
  }
Run Code Online (Sandbox Code Playgroud)

更多信息:

如果您想了解何时使用global以及何时不使用的更多信息,请查看有关变量范围php.net文档.