Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用include将变量传递到另一个页面_Php - Fatal编程技术网

Php 使用include将变量传递到另一个页面

Php 使用include将变量传递到另一个页面,php,Php,我知道有很多问题,但我有一个奇怪的情况 这是我的例子,我有一个名为Theme的类,它有一个包含主题部分的函数 class Theme { function getThemePart($part, $lang) { include_once 'theme/theme.'.$part.'.php'; } } 在我的index.php页面中,我调用它 $theme->getThemePart('footer', $lang); 在这里之前这很正常,但我还有一个$lang变量。

我知道有很多问题,但我有一个奇怪的情况

这是我的例子,我有一个名为Theme的类,它有一个包含主题部分的函数

class Theme {
  function getThemePart($part, $lang) {
    include_once 'theme/theme.'.$part.'.php';
  }
}
在我的index.php页面中,我调用它

$theme->getThemePart('footer', $lang);
在这里之前这很正常,但我还有一个$lang变量。我在index.php中声明它,但在theme.footer.php文件中也使用它。像这样,

<footer class="sticky-footer">
    <div class="container-fluid copyright">
        <span class="float-right"><?=$lang['footer]?><a href="<?=$lang['footer_link]?>" target="_blank"><u><?=$theme->escLang('footer_jc','html')?></u></a></span>
    </div>
</footer>

您的“页脚”文件仅存在于getThemePart函数中。因此,它不“知道”任何在外部声明的内容

您会注意到,即使是
{$theme}
对象实际上也是未定义的(您可以改为使用
$this
使其工作)

您需要做的是传递对主题元素需要知道的“世界”或环境的某种引用(这将是一种依赖注入):

您可以将其存储在主题中:

private $env;

public function setEnv($env) {
    $this->env = $env;
}
现在,如果您使用
$theme->setEnv($env)
初始化主题,那么在include中您将能够调用
{$this->env['lang']}
。或者您可以构建一个辅助函数,或者更好的是,声明一个允许您编写
$this->lang
的函数

就我个人而言,我通常更喜欢一种不同的方法,使用
preg\u replace\u callback()

使用
$this->env[name]
的内容替换像
{{name}}
这样的序列,您的“footer”文件只存在于gethemepart函数中。因此,它不“知道”任何在外部声明的内容

您会注意到,即使是
{$theme}
对象实际上也是未定义的(您可以改为使用
$this
使其工作)

您需要做的是传递对主题元素需要知道的“世界”或环境的某种引用(这将是一种依赖注入):

您可以将其存储在主题中:

private $env;

public function setEnv($env) {
    $this->env = $env;
}
现在,如果您使用
$theme->setEnv($env)
初始化主题,那么在include中您将能够调用
{$this->env['lang']}
。或者您可以构建一个辅助函数,或者更好的是,声明一个允许您编写
$this->lang
的函数

就个人而言,我通常更喜欢一种不同的方法,使用
preg\u replace\u callback()
$this->env[name]
的内容替换像
{{name}}
这样的序列