我有一个小类来显示下面的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
1条答案
按热度按时间eimct9ow1#
正如Ken Lee在注解中正确指出的那样,如果
isset($_SESSION['flash_notifications'])
为false,那么就缺少了return
语句。请执行以下操作: