What are the potential pitfalls of storing object instances in PHP sessions?

Storing object instances in PHP sessions can lead to serialization issues, increased memory usage, and potential security vulnerabilities if the object contains sensitive data. To avoid these pitfalls, it is recommended to store only primitive data types in sessions and recreate the object instance when needed.

// Storing only primitive data types in sessions
$_SESSION['user_id'] = $user->getId();
$_SESSION['user_name'] = $user->getName();

// Recreating the object instance when needed
$user = new User($_SESSION['user_id'], $_SESSION['user_name']);