使用PHP会话向用户发送消息

I have a session class as follows:

<?php

class Session {

    function __construct() {
        if (empty(session_id())) {
            session_start();
        }
    }

    function AddMessage($msg="") {
        if (!is_array($_SESSION['messages'])) {
            $_SESSION['messages'] = [];
        }
        array_push($_SESSION['messages'], $msg);
    }

    function GetMessages() {
        $messages = $_SESSION['messages'];
        unset($_SESSION['messages']);
        return $messages;
    }

}

?>

Also there is a php file in my layouts directory:

<?php if (!empty($_SESSION['messages'])) { ?>
<div class="messages">
<ul>
<?php
    $messages = $session->GetMessages();
    foreach ($messages as $message) {
        echo "<li class=\"message\">{$message}</li>";
    }
?>
</ul>
</div>
<?php }?>

This piece of code above is included at the top of my pages. The problem is that in case of single-page submission handling -done in the middle of the page - the messages are printed out before I set it with the AddMessage() method.

Is there a simple way to get around this issue, or I have to rethink my code flow?