所以我想知道当在多个php文件中使用变量名时是否可以从特定的php文件中获取变量。 一个例子是这样的:
<header>
<title>
<?php echo $var1; ?>
</title>
</header>
page1.php具有
$var1 = 'page1'
page2.php有
$var1 = 'page2'
footer.php应该有
<a href="">$var1 from page1</a><a href="">$var1 from page2</a>
好吧,这个例子有点抽象,但是就我所能做到的一样短.我想你明白我的意思! 这就是我追求的页脚! 有任何解决方案吗?
- 2021-1-121 #
- 2021-1-122 #
您还可以使用会话来传递少量信息.您将需要具有session_start(); 在使用会话的PHP页面顶部,否则将无法访问变量
page1.php
<?php session_start(); $_SESSION['superhero'] = "batman"; ?> <a href="page2.php" title="">Go to the other page</a>
page2.php
<?php session_start(); // this NEEDS TO BE AT THE TOP of the page before any output etc echo $_SESSION['superhero']; ?>
- 2021-1-123 #
使用
include 'page1.php'
第二页中的一个选项是一个选项,但它会生成未定义变量的警告和错误。
可以通过三种方法在一个PHP文件中使用一个php文件的变量:
use session to pass variable from one page to another
method:
first you have to start the session in both the files using php commandsesssion_start();
然后在第一个文件中考虑您有一个变量
$x='var1' ;now assign value of $x to a session variable using this:
$_SESSION['var']=$x;
now getting value in any another php file:
$y=$_SESSION['var'];//$y is any declared variable使用get方法并在单击链接时获取变量
方法<a href="page2.php?variable1=value1&variable2=value2">clickme</a>
通过$ _GET函数在page2.php文件中获取值:
$x=$_GET['variable1'];//value1 be stored in $x
$y=$_GET['variable2'];//vale2 be stored in $y
如果要使用按钮传递变量值,则可以通过以下方法使用它:
$x='value1'
<input type="submit" name='btn1' value='.$x.'/>
在第二个PHP中
$var=$_POST['btn1'];
您也可以使用 file_get_contents
$url_a="http://127.0.0.1/get_value.php?line=a&shift=1&tgl=2017-01-01"; $data_a=file_get_contents($url_a); echo $data_a;
可以,但是最后一个include中的变量将覆盖第一个变量:
myfile.php
mysecondfile.php
test.php
输出:
我建议使用不同的变量名。