Tags
PHP , Object
Asked 3 years ago
17 Jun 2021
Views 516
Theodora

Theodora posted

Storing objects in PHP session

how to store objects in PHP session
shabi

shabi
answered Apr 27 '23 00:00

In PHP, you can store objects in the session by serializing them and then storing the serialized string in the session. Here's an example:



// Start the session
session_start();

// Define a class
class Person {
  public $name;
  public $age;
}

// Create an instance of the class
$person = new Person();
$person->name = "John";
$person->age = 30;

// Serialize the object and store it in the session
$_SESSION['person'] = serialize($person);

// Retrieve the object from the session and unserialize it
$person = unserialize($_SESSION['person']);

// Access the object properties
echo $person->name; // Output: John
echo $person->age; // Output: 30

In this example, we define a Person class, create an instance of the class, and set its properties. We then serialize the object and store it in the session using the serialize() function. To retrieve the object from the session, we unserialize the serialized string using the unserialize() function.

Note that not all objects can be serialized, so it's important to test your code thoroughly to ensure that objects are being serialized and unserialized correctly. Additionally, storing large objects in the session can impact performance, so it's best to avoid storing large amounts of data in the session if possible.
Post Answer