I'm fairly new to PHP so sorry if this is a naive question, but I want to build a php function library that utilizes a variable that is global across multiple pages. I'm using these 3 files to test:
functions.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();
?>
The report
function called by index.php
echoes Value = ABC
as expected. But when the Page2
button is clicked, the report
function called by page2.php
displays an Undefined index
error raised by $GLOBALS["var"]
in functions.php
.
I'd like to use $GLOBALS["var"]
when it is referenced from page2.php
. Can anyone tell me how to enable this? Thanks for any help!
答案 0 :(得分:4)
First of all, here are a few links you should read about $_SESSIONS
variables.
I've update your code to make you an example.
functions.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>
答案 1 :(得分:4)
Recommended: Declare your variable.. Or use isset() to check if they are declared before referencing them.
Secondly you need to define a session
<?php
function report()
{
echo "Value = ". **$_SESSION['var']**;
}
?>
and use in in all your pages :)
ie, for page 1,
<?php
session_start();
$_SESSION['var'] = "XYZ";
require('functions.php');
report();
?>
and fot page2 also,
<?php
session_start();
require ('functions.php');
report();
?>
Hope it helps :)