Php 将会话中存储的值从一页传送到另一页
我在lynda.com上看了一节课,代码对他们有效,但在我尝试的时候却不起作用。这正是他们使用的代码。可能需要一些帮助来解释它为什么不起作用Php 将会话中存储的值从一页传送到另一页,php,class,session,Php,Class,Session,我在lynda.com上看了一节课,代码对他们有效,但在我尝试的时候却不起作用。这正是他们使用的代码。可能需要一些帮助来解释它为什么不起作用 <?php class Session { public $message; function __construct(){ session_start(); $this->check_message(); } public function get_message($msg="") { if(!empty($msg
<?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);
?>
您尚未在调用页上创建对象实例。试试这个:
require_once("session_class.php");
$session = new Session();
编辑
当您从\u构造中取出检查消息()
时,会设置会话,因为在检查消息()
方法中,您有以下内容:
unset($_SESSION['message']);
它基本上会破坏您的会话,这就是为什么您会看到消息“会话未设置”
如果您想设置会话,只需删除该行。什么不起作用?消息是否在应该显示的时候不显示?是否显示了任何错误消息?没错,没有显示任何消息。我在类页面上创建了对象,请参见上面的代码,我也在调用页面上尝试了它,但没有Luckw。当我运行代码时,我的页面返回“会话未设置”。你的呢?您的确切错误是什么?这也是我得到的,但是如果您从构造中取出check_消息,会话将被设置