I am a PHP OOP newbie and I am currently learning sessions. I have created a session class which is supposed to check if session variable $_SESSION['userID']
is set, and set the login status to true; as well as set the user id.There is also a function, setVars()
to set other object properties when called:
session.php
<?php
class Session
{
public $log_in_status=false;
public $userID;
public $fname;
public $class_id;
public $email;
public function __construct()
{
session_start();
if ($_SESSION['userID'])
{
$this->log_in_status = true;
$this->userID = $_SESSION['userID'];
}
else
{
$this->log_in_status = false;
unset($_SESSION['userID']);
}
}
public function setVars($classID, $email, $fname)
{
$this->class_id = $classID;
$this->email = $email;
$this->fname = $fname;
}
}
$session = new Session();
The above class is in a require_once statement in init.php file:
<?php
#init.php
require_once("session.php");
Page1.php sets some properties in the $session instance by calling the setVars
method, and after echo them to the screen. However, page2.php is not able to echo these same values from the object properties:
<?php
# page1.php
require_once("init.php");
$class_id = 1;
$email = "test@test.com";
$fname = "Toto The Dog";
$session->setVars($class_id, $email, $fname);
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing sessions</title>
</head>
<body>
<?php
echo "Page 1 <br> <br>";
echo "objectClassID: " .$session->class_id . "<br>";
echo "objectEmail : " . $session->email . "<br>";
echo "objectFname : " . $session->fname . "<br> <br>";
echo "<a href='page2.php'>Go to Page 2</a>";
?>
</body>
</html>
//--------------------------------------------
<?php
# page2.php
require_once("init.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing sessions</title>
</head>
<body>
<?php
echo "Page 2 <br> <br>";
echo "objectClassID: " . $session->class_id . "<br>";
echo "objectEmail : " . $session->email . "<br>";
echo "objectFname : " . $session->fname . "<br> <br>";
echo "<a href='page1.php'>Go to Page 1</a>";
?>
</body>
</html>
How can I get page2.php to be able to display the $session
object properties?