I’m storing sessions in a MySQL database.
I’ve a SessionManager class which has multiple functions. However, somewhere in the class, my database class is being unloaded, and I can’t seem to find out why.
I tested to see if the class exists using:
echo (class_exists('database') === TRUE ? 'Yes' : 'No');
This is the function which is producing a fatal error telling me that the class database is not found. Note that test above returns true where the test is located in the __construct and fails specifically in this method:
public static function writeSession($sessionId, $sessionData)
{
$sessionId = session_id();
session_write_close();
session_id($sessionId);
$expiry = time() + ini_get('session.gc_maxlifetime') - 1;
$sessionId = database::getInstance()->real_escape_string($sessionId);
$sessionData = database::getInstance()->real_escape_string($sessionData);
$result = database::getInstance()->query("SELECT sessionid FROM sessions WHERE sessionid='$sessionId'");
($result->num_rows > 0) ?
database::getInstance()->query("UPDATE sessions SET sessionid='$sessionId',expiry='$expiry',sessiondata= '$sessionData' WHERE sessionid='$sessionId'")
: database::getInstance()->query("INSERT INTO sessions (sessionid,expiry,sessiondata) VALUES ('$sessionId','$expiry','$sessionData')") ;
}
Even if I try to instantiate a new object of database, the class is not found, it’s as if it disappears.
The class works, and is fine in the previous method:
public static function readSession($sessionId)
{
$sessionId = session_id();
$sessionId = database::getInstance()->real_escape_string($sessionId);
$time = time();
$result = database::getInstance()->query("SELECT sessiondata FROM sessions WHERE sessionid='$sessionId' AND expiry > $time");
if ($result->num_rows > 0) {
$row = $result->fetch_array();
return $row['sessiondata'];
}
return "";
}
Can anyone see what’s going on here?
Just two major points at the beginning:
databaseclass is missing (not unset) at some (and that) point.databaseclass definition is actually loaded.Which leads to the solution that you should require the
databaseclass definition for that function call. Put that in, and thedatabaseclass is defined. Actually I don’t understand about which part you wonder that much in your question.Classes and especially static functions are rather straight forward, you could also replace them with standard functions to a certain degree which might make your type of usage more visible and more straight forward. Don’t use language features you don’t feel common with until you do.