我有两个文件加载到页面上(body.php和footer.php)。
在身体里我有:
<?php global $pageName = "foo";?>
在页脚中我有:
<?php echo $pageName;?>
然而,它没有回应。我错过了什么吗?
答案 0 :(得分:1)
全局范围仅计入varibale所在的文件。您可以执行include footer.php
,然后您的代码将起作用。
body.php:
<?php $pageName = "foo"; //No need for the global, the varibale is already in the global scope
include 'footer.php';
?>
最后会回复#34; foo&#34;
In the official documentation you can read about variable scoping
根据评论编辑
您可以将set变量设置为Session。
所以你的body.php看起来像是:
<?php
session_start(); //IMPORTANT, this must be the first action you do.
$pageName = "foo"; //No need for the global, the varibale is already in the global scope
$_SESSION['pageName'] = $pageName;
?>
你的footer.php:
<?php
session_start(); //IMPORTANT, this must be the first action you do.
echo $_SESSION['pageName'];
?>
答案 1 :(得分:1)
您不必将全局变量定义为全局变量。 您可以在身体中使用这段代码:
<?php $pageName = 'foo'?>
这段代码在你的页脚中:
<?php global $pageName; echo $pageName //$pageName from body.php ?>
另一种方法是创建一个page.php文件,您可以在其中放置数据:
<?php
// (Inside page.php)
$pageName = 'foo';
require('header.php'); // Use $pageName in header.php without global
require('body.php'); // Use $pageName in body.php without global
require('footer.php'); // Use $pageName in footer.php without global
?>
快乐的编码!