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:
session_start();
class Person {
public $name;
public $age;
}
$person = new Person();
$person->name = "John";
$person->age = 30;
$_SESSION['person'] = serialize($person);
$person = unserialize($_SESSION['person']);
echo $person->name;
echo $person->age;
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.