PHP: Storing 'objects' inside the $_SESSION

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:

$_SESSION['object_key'] = $object;

Watch a course Learn object oriented PHP

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

$object = $_SESSION['object_key'];

It's important to note that the object stored in session needs to be serializable, otherwise it will not be able to be stored in the session.

<?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;

It is also important to note that if you are storing large objects in $_SESSION, it could potentially cause your sessions to become large and consume a lot of memory on the server, so it's important to be mindful of the amount of data you are storing in $_SESSION.