gpt4 book ai didi

php - 跨多个网页使 PHP 变量成为全局变量

转载 作者:行者123 更新时间:2023-12-04 20:21:56 24 4
gpt4 key购买 nike

我是 PHP 的新手,如果这是一个幼稚的问题,我很抱歉,但我想构建一个 php 函数库,该函数库利用跨多个页面的全局变量。我正在使用这 3 个文件进行测试:

函数.php

<?php
function report()
{
echo "Value = ".$GLOBALS["var"];
}
?>

index.php

<?php
$var = "ABC";
require "functions.php";
echo "<h1>index.php</h1>";
report();
?>
<br /><br />
<input type=button onClick="location.href='page2.php'" value="Page2">

page2.php

<?php   
require "functions.php";
echo "<h1>page2.php</h1>";
report();
?>

index.php 调用的report 函数按预期响应Value = ABC。但是,当单击 Page2 按钮时,page2.php 调用的 report 函数会显示 Undefined index 错误通过 $GLOBALS["var"]functions.php 中。

page2.php 引用它时,我想使用 $GLOBALS["var"]。谁能告诉我如何启用它?感谢您的帮助!

最佳答案

首先,这里有一些您应该阅读的关于$_SESSIONS 变量的链接。

我已经更新了你的代码,让你成为一个例子。

函数.php

<?php
function report()
{
if(isset($_SESSION['var']))
echo "Value = ". $_SESSION['var'];
}
?>

index.php

<?php
session_start();
?>
<html>
<head>
</head>
<body>
<?php

$_SESSION['var'] = "ABC";

require('functions.php');
echo "<h1>index.php</h1>";

report();
?>
<br><br>
<input type="button" onClick="location.href='page2.php'"
value="Page2">
</body>

page2.php

<?php 
session_start();
?>
<html>
<head>
</head>
<body>
<?php
require ('functions.php');
echo "<h1>page2.php</h1>";
report();
?>
</body>
</html>

关于php - 跨多个网页使 PHP 变量成为全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com