【问题标题】:Carrying a value stored in a session from one page to another将存储在会话中的值从一个页面传送到另一个页面
【发布时间】:2011-06-18 13:21:51
【问题描述】:

我正在 lynda.com 上观看课程,代码对他们有效,但在我尝试时不起作用。这是他们使用的确切代码。可以使用一些帮助来解释它为什么不起作用。

<?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();


?>

在调用页面上

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

 function output_message($msg="") {
    if (!empty($msg)) { 
      return "<p>$msg</p>";
    } else {
      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);

?>

【问题讨论】:

  • 究竟是什么不起作用?应该显示的消息是否没有显示?是否显示任何错误消息?
  • 正确,没有消息显示。

标签: php class session


【解决方案1】:

您尚未在调用页面上创建对象实例。试试这个:

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

编辑

当您从__construct 中取出check_message() 时,会设置SESSION,因为在您的check_message() 方法中,您有这个:

unset($_SESSION['message']);

它基本上会破坏您的会话,这就是您看到“会话未设置”消息的原因。

如果您想设置会话,只需删除该行即可。

【讨论】:

  • 我在类页面上创建了对象,参见上面的代码,我也在调用页面上尝试过,但没有成功
  • 当我运行您的代码时,我的页面返回“会话未设置”。你的呢?您的确切错误是什么?
  • 这也是我得到的,但如果你从构造中取出 check_message 会话将被设置
猜你喜欢
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
相关资源
最近更新 更多