So I was practicing arround with some oop and tried to make a basic oop User class I tried making my system so that on every page I can just include config.php and everthing I need gets loaded in, but for some reason as soon as I try to login it throws me this error :
Fatal error: Call to a member function LogIn() on a non-object
config.php :
<?php
session_start();
// Mysql details
$username = "torlolol";
$password = "torlolol";
$hostname = "localhost";
$database = "torlolol";
// Autoloads classes when needed
function __autoload($class_name) {
include 'Classes/' . $class_name . '.php';
}
$db = new DBConnector($hostname, $username, $password);
// If there is no user in the session stored make a new one otherwise unserialize it
if(empty($_SESSION['user']))
$user = new User();
else
$user = unserialize($_SESSION['user']);
function onExit()
{
//When exiting the page serialize the user object and store it in the session
$_SESSION['user'] = serialize($user);
}
register_shutdown_function("onExit")
?>
login.php
<?php
include "config.php";
global $user;
$user->LogIn();
?>
User class :
class User {
public $Logged = false;
public function LogIn()
{
$this->Logged = true;
}
public function LogOut()
{
$this->Logged = false;
}
}
?>
index.php :
<?php
include "config.php";
global $user;
if ($user->Logged != true)
echo '<form action="login.php" method="post">Username :<input type="text" name="username" /> Password :<input type="password" name="password" /> <input type="submit" value="Login" /></form>';
else
echo '<form action="logout.php" method="post"><input style="submit" value="Logout" /></form>';
So why does it throw out that error ? And why isn't it happening in the index file :S ?>
You have to include the class-files BEFORE you start the session, otherwise serialized objects will not be loaded correctly. Unfortunately...
Try by removing,
Because when your are including file, $user will automatically include in your file.
If you unserialize an object, which class wasn't yet declared, it gets unserialized into a
__PHP_Incomplete_Class
, which obviously doesn't have aLogIn
method. So you either need to include the file manually, or register anunserialize_callback_func
:in the config.php file you register a shutdown function that set $_SESSION['User'] with an instance of User (the $user variable)... but because of the way you manage instancied classes (by using global variable) you need to redeclare
global $user;
in theonExit
function.i personnally recommand to have a main global class that handle the instances of the classes you need in your whole application.
edit: look at my answer here
Here's a class, which allows to trace changes on global variables:
Use it like this:
Whill output
While this version CSysTracer tracks changes on globals, you might create a variation of traceGlobalVariable() to trace changes for session variables or e.g. method-calls.