尝试修改Flash消息功能,但无法正常工作。 $_SESSION[$type][$name]
等格式是不可接受的?
function flash($type = '', $name = '', $message = '', $class = '', $dismiss = '' )
{
//We can only do something if name exists
if($name)
{
//No message, create it
if($message && empty($_SESSION[$type][$name]))
{
$_SESSION[$type][$name] = $message;
$_SESSION[$type][$name][$class] = $class;
$_SESSION[$type][$name][$dismiss] = $dismiss;
}
//Message exists, display it
else if($_SESSION[$type][$name] && empty($message))
{
echo '<div class="'.$_SESSION[$type][$name][$class].'">'.$_SESSION[$type][$name].' '.$_SESSION[$type][$name][$dismiss].'</div>';
unset($_SESSION[$type]);
}
}
}
用法是:
// set a message
<?php flash( 'error', 'test', 'whats up?', 'info', 'TRUE' ); ?>
// display a message
<?php flash( 'test' ); ?>
答案 0 :(得分:0)
我认为你遇到的问题是你在这里用数组覆盖了$message
:
$_SESSION[$type][$name] = $message; // Sets the message
$_SESSION[$type][$name][$class] = $class; // Overwrites it with an array
您需要做的就是将消息保存到同一个数组中(并确保您提供的索引永远不能与$class
或$dismiss
相同。例如:< / p>
$_SESSION[$type][$name]['messagetext'] = $message;
然后,当然,更新代码的显示部分以使用该索引:
echo '<div class="'.$_SESSION[$type][$name][$class].'">'.$_SESSION[$type][$name]['messagetext'].' '.$_SESSION[$type][$name][$dismiss].'</div>';
编辑:在评论中讨论之后,最终代码看起来像这样,前提是每个$type
和$name
组合只会有一条消息:
function flash($type = '', $name = '', $message = '', $class = '', $dismiss = '' )
{
//We can only do something if name exists
if($type)
{
//No message, create it
if($message && empty($_SESSION[$type][$name]))
{
$_SESSION[$type][$name]['message'] = $message;
$_SESSION[$type][$name]['class'] = $class;
$_SESSION[$type][$name]['dismiss'] = $dismiss;
}
//Message exists, display it
else if($_SESSION[$type] && empty($message))
{
foreach($_SESSION[$type] as $name=>$array) {
echo '<div class="'.$_SESSION[$type][$name]['class'].'">'.$_SESSION[$type][$name]['message'].' '.$_SESSION[$type][$name]['dismiss'].'</div>';
}
unset($_SESSION[$type]);
}
}
}
用法是:
// set a message
<?php flash( 'error', 'test', 'whats up?', 'info', 'TRUE' ); ?>
// display all $type= 'error' messages
<?php flash( 'error' ); ?>