Tags
Asked 3 years ago
17 Jun 2021
Views 250
Esteban

Esteban posted

Store Object in PHP Session

Store Object in PHP Session
hanuman

hanuman
answered Apr 27 '23 00:00

In PHP, you can store an object in a session by first serializing the object and then storing it in the session.

Here is an example of how to store an object in a PHP session:



// Start session
session_start();

// Create an object
class Person {
    public $name;
    public $age;
}

$person = new Person();
$person->name = "John";
$person->age = 30;

// Serialize the object
$serialized_person = serialize($person);

// Store the serialized object in the session
$_SESSION['person'] = $serialized_person;

// Retrieve the serialized object from the session
$serialized_person = $_SESSION['person'];

// Unserialize the object
$person = unserialize($serialized_person);

// Access the object properties
echo $person->name; // Output: John
echo $person->age; // Output: 30
In this example, we create a Person object, serialize it, store it in the session under the  person  key, retrieve it from the session, unserialize it, and access its properties.


Note that the object must be serializable in order to store it in the session. If the object contains resources or references, it may not be serializable and therefore cannot be stored in the session.
Post Answer