How can PHP objects differentiate between being generated or retrieved from a session?

When retrieving an object from a session in PHP, it can be difficult to differentiate between an object that was previously stored in the session and a newly generated object. One way to solve this issue is to include a flag in the session data that indicates whether the object is being retrieved or generated. By checking this flag, you can determine the origin of the object and handle it accordingly.

// Check if the object is being retrieved or generated from the session
if(isset($_SESSION['object']) && isset($_SESSION['object']['isRetrieved']) && $_SESSION['object']['isRetrieved'] === true) {
    // Object is being retrieved from the session
    $object = $_SESSION['object']['data'];
} else {
    // Object is being generated
    $object = new YourObject();
    
    // Store the object in the session with the flag indicating it was generated
    $_SESSION['object'] = [
        'isRetrieved' => false,
        'data' => $object
    ];
}