开发者

Carrying a value stored in a session from one page to another

I was watching a lesson on lynda.com and the code works for them but will not work when I try it. This is the exact code they use. Could use some help to why it is not working.

<?php
 class Session
{
public $message;

function __construct(){
    session_start();
    $this->check_message();
}

 public function get_message($msg="") {
  if(!empty($msg)) {
    // then this is "set message"

    $_SESSION['message'] = $msg;
  } else {
    // then this is "get message"
        return $this->message;
  }
}

private function check_message() {
    // Is there a message stored in the session?
    if(isset($_SESSION['message'])) {
        // Add it as an attribute and erase the stored version
     $this->message = $_SESSION['message'];
     unset($_SESSION['message']);
    } else {
     $this->message = "";
    }
   }
 }

  $session = new Session();


?>

and on the calling page

<?php
 require_once("session_class.php");

 function output_message($msg="") {
    if (!empty($msg)) { 
      return "<p>$msg</p>";
    } else {开发者_如何学JAVA
      return "";
   }
}

if (isset($_SESSION['message'])) {
echo "session is set";
} else {
echo "session is not set";
} 

$message = $session->get_message("working"); 

//$message = "Working";THIS WILL WORK

echo output_message($message);

?>


You haven't created an object instance on the calling page. Try this:

require_once("session_class.php");
$session = new Session();

EDIT

When you take out check_message() from the __construct, the SESSION is set because in your check_message() method, you have this:

unset($_SESSION['message']);

It basically destroys your session, that's why you see that message "session is not set".

If you want the session to be set, simply delete that line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜