W3docs

PHP: Storing 'objects' inside the $_SESSION

In PHP, the $_SESSION superglobal is used to store data that needs to persist across multiple page requests.

In PHP, the $_SESSION superglobal is used to store data that needs to persist across multiple page requests. The data stored in $_SESSION is typically in the form of key-value pairs, where the key is a string and the value can be any data type, including objects. To store an object in $_SESSION, you can simply assign it to a key like this:

Example of storing an object in $_SESSION in PHP

$_SESSION['object_key'] = $object;

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can then retrieve the object from $_SESSION later on by accessing the key:

Example of retrieving the object from $_SESSION in PHP

$object = $_SESSION['object_key'];

Note that PHP automatically serializes objects when storing them in sessions. If your object contains unserializable resources (like database connections), you may need to implement __sleep() and __wakeup() methods to control the process.

Example of implementing __sleep() for session storage in PHP

<?php

class Example
{
  public $name;
  public $age;
  public function __sleep()
  {
    return ['name', 'age'];
  }
}

$example = new Example();
$example->name = 'John Doe';
$example->age = 30;

$_SESSION['example'] = $example;

Storing large objects in $_SESSION can increase session size and consume significant server memory. Be mindful of the amount of data you store.