尝试/捕获和会话有趣的结果

时间:2015-08-11 00:07:10

标签: php class session try-catch

我有这些方法来处理名为KD的类中的脚本通知。

private static $notice=array(); 

public static function SetNotice($type, $text){
    self::$notice[] = array('type'=>$type, 'text'=>$text);
    $_SESSION['notices'] = self::$notice;
}

public static function notice(){
    if($_SESSION['notices']){
        foreach($_SESSION['notices'] as $key=>$note){
            $html .= '<div class="notice-'.$note['type'].'"><p class="icon">'.$note['text'].'</p></div>';
        }
        return $html;
    }
}

添加新通知:

KD::SetNotice('type','message');

显示通知:

KD::notice()

我也有这种方法,我通常会在所有脚本的末尾添加:

public static function redirect($to = http_referer){  //  http_referer is a defined constant to replace $_SERVER['HTTP_REFERER']
    if(!headers_sent()){  return exit(header('Location:'.$to));  } 
    else{  return print_r('<script>window.location = "'.$to.'";</script>');  }
}

使用示例:

/**
 * Script to be executed
 */
if($action){
    KD::SetNotice('success','All good');
} else {
    KD::SetNotice('error','Something went wrong');
}
KD::redirect();  //  redirects the user back

执行后的目标网页:

<!-- somewhere on that page where I want to show messages  -->
<?=KD::notice()?>

这完美无缺。所有通知现在按照它们设置的顺序返回。

我的问题:
但是当我在着陆页上的混合中添加try/catch块时,其中包含KD::SetNotice();,之前的所有通知都会被删除或覆盖:

#   script.php

if($action){
    KD::SetNotice('success','All good');
} else {
    KD::SetNotice('error','Something went wrong');
}
KD::redirect();


#   landing-page.php

echo KD::notice();  //  returns all notices so far

/**
 *   I found that it is neccecary to use try/catch when using DESCRIBE in order to prevent error messages to be displayed when checking if a table exists.
 */
try {
    $describe = $dbh->query('DESCRIBE users');
    $table_exists = true;
} catch (PDOException $e) {
    KD::SetNotice('warning','Table does not exists. Please create it in order to continue.');
    $table_exists = false;
}
KD::SetNotice('info','you should know');

KD::notice();  //  only notices set within try/catch is returned, along with notices set after...

以某种方式在SetNotice内使用try/catch - 方法时,会覆盖保存通知的会话。
如果我删除try/catch,则会返回脚本和目标网页上最后一个设置的通知。

实际上。 try/catch正在干扰包含通知的会话。之前设置的每个通知都将被删除或覆盖......

我不知道这是否是代码,以帮助我弄清楚为什么会发生这种情况,但请告诉我是否有我不知道的事情。

提前致谢。

更新
我刚刚测试过脚本执行后没有刷新页面。意思是我遗漏了KD::redirect - 方法,现在显示所有通知 因此,当我重新定向用户时问题就出现了......

更新2:可能的解决方案
在脚本结束时重定向用户后,$notice - 数组当然被重置为空。只有$_SESSION['notices']中的通知仍可在着陆页上使用 因此,当再次使用SetNotice() - 方法时,我&#34;覆盖&#34;带有新通知的SESSION 这导致在着陆页上使用<?=KD::notices()?>时仅返回此页面加载设置的通知..

当我想到它时,它是有道理的。所以我在SetNotice() - 方法的开头添加了这个:

#   make sure existing notices is kept after redirection
    if($_SESSION['notices']){
        foreach($_SESSION['notices'] as $key=>$note){  self::$notice[]=array('type'=>$note['type'],'text'=>$note['text']);  }
    }
//

0 个答案:

没有答案