【问题标题】:share variable into multi include (php)将变量共享到多包含(php)中
【发布时间】:2017-05-20 07:57:11
【问题描述】:

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

在 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 中都是空的

为什么?

感谢回复

纪尧姆

【问题讨论】:

  • 全局 $a; $a = '最大';

标签: php include global-variables share


【解决方案1】:

这是一个需要避免的陷阱。如果您需要访问您的变量 $a 在函数中,你需要说“global $a;”在 该功能的开始。您需要为每个功能重复此操作 在同一个文件中。

示例:

只会显示错误。

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

【讨论】:

  • Okkzzz .. 然后请在我的回答中勾选标记为正确... :)
猜你喜欢
  • 1970-01-01
  • 2021-05-13
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多