通过包含的文件传递并打印 $_GET 变量 [英] Pass and print a $_GET variable through an included file
问题描述
我有一个 php 文件index.php 和它的 url 是 index.php?var=item
我在 index.php
I have a php file
index.php and its url is index.php?var=item
I defined get variable in index.php
在 index.php 中
in index.php
<?php
require "included.php";
$var=$_GET['var'];
?>
我在我的 included.php
中回显了这个变量,如下所示
I echoed this variable in my included.php
like below
在included.php中
in included.php
<?php
echo $var;
?>
当我启动 index.php?var=item
时,它显示一个错误,即 included.php
中没有定义 var?
When I launch index.php?var=item
, its shows an error that var is not defined in included.php
?
如何解决这个问题?我想从 url 在 index.php
中定义一些变量,并在包含的文件中做一些工作.
How to overcome this? I want to define some variables in index.php
from url and do some staff in included file.
推荐答案
在包含另一个文件之前在 PHP 代码中设置的任何变量都可以在那里工作.被包含的文件不会注意到在被包含后声明或设置的任何其他变量.
Any variables set up in your PHP code before including another file would work there. The included file won't be aware of any other variable that was declared or set after it was included.
在 index.php
中,这样做:
<?php
if(isset($_GET['var'])) {
$var=$_GET['var'];
}
require "included.php";
?>
然后访问 $var
值,就像您已经在 included.php
中尝试做的那样.
Then access the $var
value like you are already trying to do in included.php
.
当我写这个答案时,我可以看到刚刚发布了一个类似的答案.抱歉还是发布了它,我认为它包含了更多的解释.
And as I am writing this answer, I can see that a similar answer has just been posted. Sorry for posting it anyway, I think it includes a bit more explanation.
这篇关于通过包含的文件传递并打印 $_GET 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!