我有一个三层树来显示页面上的内容。它使用include根据URL显示特定的PHP页面。不会发生的情况是变量在包含的PHP文件中不被理解。
index . php
// example url http://fakesite.com/?color=red&user=999
$user = $_GET['user'];
if ($_GET['color'] == 'red')
{$color = 'red';}
elseif ($_GET['color'] == 'white')
{$color = 'white';}
else
{$color = 'blue';}
global $color;
global $user;
include 'page2.php';
page2.php
global $color;
global $user;
echo 'hi '.$user.'I hear you like '.$color;
根本不需要那些$global
行。在主脚本中定义的任何变量都在include
d文件中定义。它基本上就像在include
d文件中获取代码并将其推到include
调用的位置(有几个例外)
这一行:
include_once 'page2.php;
应改为:
include_once 'page2.php';
你缺少一个引号
你试过删除所有这四个全局行吗?我不知道这是不是问题所在,但它们根本没有必要!
当包含或要求一个文件时,上面声明的所有变量都可用于被包含/要求的文件。
如果这还不能解决问题,也许你在include中设置了错误的路径。
index.php
<?php
$user = $_GET['user'];
if ($_GET['color'] == 'red')
{$color = 'red';}
elseif ($_GET['color'] == 'white')
{$color = 'white';}
else
{$color = 'blue';}
include 'page2.php';
?>
page2.php
<?php
echo 'hi '.$user.'I hear you like '.$color;
?>
全球示例function dosomethingfunky(){
global $user, $color;
echo 'hi '.$user.'I hear you like '.$color;
}