难以传递变量包括使用全局变量
我有一个三层树,用于在页面上显示内容。它使用 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;
I have a three tier tree for displaying content on a page. It uses includes to display specific PHP pages based on the URL. What doesn't happen is the variables are not understood in included PHP files.
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根本不需要这些
$global
行。主脚本中定义的任何变量都在include
d 文件中定义。这基本上就像获取include
d 文件中的代码并将其推入include
调用的位置(有一些例外)There is no need at all for those
$global
lines. Any variables defined in the main script are defined in theinclude
d file. It's basically like taking the code in theinclude
d file and shoving it in the place of theinclude
call (with a few exceptions)此行:
应更改为:
您缺少报价。
This line:
should change to:
You have a missing quote.
您是否尝试过删除所有这四条全局线?我不知道这是否是问题所在,但它们根本没有必要!
当包含或需要文件时,上面声明的所有变量都可用于包含/需要的文件。
如果这没有解决问题,也许你的包含路径错误。
Have you tried removing ALL those four global lines? I don't know if that's the problem, but they're not necessary at all!
When including or requiring a file all the variables declared above are available to the included/required file.
If that didn't solve it, maybe you have the wrong path on include.
index.php
page2.php
全局示例
index.php
page2.php
global example