Myles Melia
Myles Melia

Reputation: 11

Storing objects inside a session

I am attempting to store an object into $_SESSION but I am having a few issues doing so.

Here is the class:

class Profile {
            var $username;
            var $password;
            var $admin;

            function __construct($username, $password) {
                $this->username = $username;
                $this->password = $password;
            }

            function getName() {
                return $this->username;
            }

            function isAdmin() {
                return $this->admin;
            }

            function setAdmin($admin) {
                return $this->admin = $admin;
            }
        }

and I am storing the data inside the session this way:

$_SESSION['profile'] = serialize($profile);

and when I attempt to load that data in another class I receive an error:

Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition in C:\wamp64\www\login\hidden.php on line 33

I have dumped the loaded object to check if it is actually being loaded and it appears the object has been unserialized and I can see all the data itself inside the object.

$profile = unserialize($_SESSION['profile']);
var_dump($profile);

and I receive this on my localhost when dumping it:

C:\wamp64\www\login\hidden.php:31:
object(__PHP_Incomplete_Class)[1]
  public '__PHP_Incomplete_Class_Name' => string 'Profile' (length=7)
  public 'username' => string 'myles' (length=5)
  public 'password' => string 'myles' (length=5)
  public 'admin' => boolean true

I am truly lost and have no idea what to do if someone could help me, that would be great.

Upvotes: 0

Views: 698

Answers (1)

miken32
miken32

Reputation: 42716

Before unserializing you need to do the same thing you would before creating an instance of the object normally:

$profile = new Profile("u", "p");

That is, make sure you have included all the files that define that class. That is what the error message is trying to tell you:

Please ensure that the class definition "Profile" of the object you are trying to operate on was loaded before unserialize() gets called

So do something like this:

<?php
require_once '/path/to/Profile.class.php';
session_start();
$profile = unserialize($_SESSION['profile']);

Upvotes: 1

Related Questions