php 如何添加一次会话消息,然后显示给用户

amrnrhlw  于 2022-12-02  发布在  PHP
关注(0)|答案(1)|浏览(335)

我有一个小类来显示下面的flash通知

class Flash
{

    const SUCCESS = 'success';
    const INFO = 'info';
    const WARNING = 'warning';

    public static function addMessage(string $message, string $type = 'success'): void
    {
        // Create array in the session if it doesn't already exist
        if (! isset($_SESSION['flash_notifications'])) {
            $_SESSION['flash_notifications'] = [];
        }

        // Append the message to the array
        $_SESSION['flash_notifications'][] = [
            'body' => $message,
            'type' => $type
        ];
    }

    public static function getMessages(): mixed
    {
        if (isset($_SESSION['flash_notifications'])) {
            $messages = $_SESSION['flash_notifications'];
            unset($_SESSION['flash_notifications']);

            return $messages;
        }
    }

然后在下面的示例中将消息添加到会话时

if(empty($_POST['email'])){

   //do something here

} else {
  
    Flash::addMessage('Successful', Flash::SUCCESS);
}

则如果有消息则显示它

<?php foreach (Flash::getMessages() as $message): ?>
    <div class="alert alert-<?= $message['type'] ?>">
        <?= $message['body'] ?>
    </div>
<?php endforeach; ?>

但我在页面加载时收到以下内容

Uncaught TypeError: Flash::getMessages(): Return value must be of type mixed, none returned
eimct9ow

eimct9ow1#

正如Ken Lee在注解中正确指出的那样,如果isset($_SESSION['flash_notifications'])为false,那么就缺少了return语句。
请执行以下操作:

public static function getMessages(): array
    {
        if (isset($_SESSION['flash_notifications'])) {
            $messages = $_SESSION['flash_notifications'];
            unset($_SESSION['flash_notifications']);

            return $messages;
        }
        
        return [];
    }

相关问题