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

share variable into multi include (php)

我不明白为什么我的变量在 multi include 之后没有设置。

在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");

}

在 accueil.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中设置的所有变量在accueil.php

中为空

为什么?

感谢回复

纪尧姆

Here is a pitfall to avoid. In case you need to access your variable $a within a function, you need to say "global $a;" at the beginning of that function. You need to repeat this for each function in the same file.

示例:

只会显示错误。

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();