2012-10-09 18 views
0

我想從一個類函數內設置一個會話變量的值,並在稍後的時間在同一個類的不同函數內比較該會話值。這些函數都不在__construct()函數中。比較一個php類中的會話變量?

問題似乎是比較永遠不會返回true。

<?php 
session_start(); 
$class = new Class(); 
?> 

blah blah blah 

<script type="text/javascript"> 
    // Ajax function to call PHP that creates new Class isntance and executes a Class->function(); 
    setInterval('checkNew()', 10000); 
</script> 

blah blah blah 

// Another Ajax Function that calls creates a new Class isntance and executes the initial Class->function(); 
<body onload="getMessages();"> 

blah blah blah 

下一個功能片段是從ajax調用的腳本運行的。 這是爲了比較這個$_SESSION['last_sms']以後的不同功能。

// Check the now() stamp of the most recent message loaded 
$recent_msg_query = "SELECT date_received FROM messages ORDER BY date_received DESC LIMIT 1"; 
$recent_statement = $this->db_handle->prepare($recent_msg_query); 
$recent_statement->execute(); 
$most_recent = $recent_statement->fetch(PDO::FETCH_NUM); 
$_SESSION['last_sms'] = $most_recent[0]; 

這是類中的函數是應該做的比較中,每十秒鐘(通過setInterval('checkNew()', 10000);

public function checkNew() 
{ 
    // Check the now() stamp of the most recent message loaded and compares it 
    // to a stored now() stamp. 
    $recent_msg_query = "SELECT date_received FROM messages ORDER BY date_received DESC LIMIT 1"; 
    $recent_statement = $this->db_handle->prepare($recent_msg_query); 
    $recent_statement->execute(); 
    $most_recent = $recent_statement->fetch(PDO::FETCH_NUM); 

    if (!isset($_SESSION['last_sms'])) { 
     $_SESSION['last_sms'] = $most_recent[0]; 
    } 

    if ($_SESSION['last_sms'] !== $most_recent[0]) { 
     echo "New message(s) available, refresh."; 
    } else { 
     echo "No new messages yet."; 
    } 
} 

當我發送新郵件,網頁仍然說「不新消息呢。「你們能幫我弄清楚我在這裏走的路嗎?這$_SESSION stuff是目前爲止唯一不能工作的東西。

+0

在你的checkNew()函數中運行'var_dump($ _ SESSION ['last_sms'])'看看它是否被設置 – christopher

+2

在AJAX處理程序腳本中調用了'session_start()'_also_? (無論'getMessages()'回撥到) –

+0

@MichaelBerkowski號 – jdstankosky

回答

1

session_start()不僅僅用作會話發起者。每撥腳本都必須在上調用該腳本,該腳本嘗試讀取或寫入$_SESSION。由於您的AJAX處理程序腳本與生成它們被調用的頁面的主PHP腳本分離,並且它們作爲完全獨立的PHP腳本運行,所以您還必須在處理PHP腳本的AJAX上調用session_start()