将变量共享到多个包含(php)

将变量共享到多个包含(php),php,include,global-variables,share,Php,Include,Global Variables,Share,我不明白为什么我的变量在多重包含之后没有设置 在header.php中,我有一个变量$a public function defaultShow(){ include(dirname(__FILE__)."/../view/app/header.php"); include(dirname(__FILE__)."/../view/app/accueil.php"); include(dirname(__FILE__)."/../view/app/

我不明白为什么我的变量在多重包含之后没有设置

在header.php中,我有一个变量$a

public function defaultShow(){

        include(dirname(__FILE__)."/../view/app/header.php");
        include(dirname(__FILE__)."/../view/app/accueil.php");
        include(dirname(__FILE__)."/../view/app/footer.php");

}
在acueil.php中,设置了$a。这很有效

但是如果我的代码是

public function defaultShow(){

        self::includeView("app/header");        
        self::includeView("app/accueil");
        self::includeView("app/footer");

}

public static function includeView($view){      
        include dirname(__FILE__)."/../view/".$view.".php";
}
accueil.php已加载,但此文件中的$a为空

在header.php中设置的所有变量在acueil.php中都为空

为什么?

谢谢你的回复

纪尧姆

这里有一个要避免的陷阱。以防您需要访问变量 $a在函数中,您需要在 该功能的开始。您需要对每个函数重复此操作 在同一个文件中

示例:

include('front.php');

function foo() {
  global $a;
  echo $a;
}

function bar() {
  global $a;
  echo $a;
}

foo();
bar();
只会显示错误。

include('front.php');
global $a;

function foo() {
  echo $a;
}

function bar() {
  echo $a;
}

foo();
bar();
正确的方法是:

include('front.php');

function foo() {
  global $a;
  echo $a;
}

function bar() {
  global $a;
  echo $a;
}

foo();
bar();

全球美元/年$a=‘最大值’;好的。。然后,请在“我的答案”的正确位置打勾…:)