我是一个PHP初学者,我想做一个静态方法,如果它的参数是空的,它会显示消息。如果不是,它将给定的消息设置为一个静态变量,以供以后使用。但是当我调用方法来设置消息时,然后在另一个页面中调用它来显示消息。没有出现。
下面是我为"session.php"编写的部分代码:
class Session {
public static $message;
public static function notify($message = ""){
if(!empty($message)){
self::$message = $message;
} else {
return self::$message;
}
}
}
$session = new Session();
"add_user.php":
<?php
require_once '../helper/session.php';
?>
<?php
if (isset($_POST["submit"])) {
$user->username = $_POST["username"];
$user->password = $_POST["password"];
$user->first_name = $_POST["first_name"];
$user->last_name = $_POST["last_name"];
if($result = $user->add_user()){
Session::notify("New user added");
redirect_to("../view/login.php");
} else { Session::notify("Cannot add new user"); }
}
?>
"login":
<?php
require_once "../control/add_user.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="../stylesheet/login.css" />
<title>Welcome to Harmony</title>
</head>
<body>
<header>
<h2>Harmony</h2>
</header>
<section>
<div id="formStyle">
<h3>Login or Signup:</h3>
<form action="login.php" method="post">
<p><label for="username">Username: </label>
<input type="text" name="username" value="" placeholder="Username"/></p>
<p><label for="password">Password: </label>
<input type="text" name="password" value="" placeholder="Password"/></p>
<input type="submit" name="submit" value="Submit" />
<input type="button" name="sign_up" value="Sign up" onClick="parent.location='add_user.php'">
</form>
<?php echo Session::notify(); ?>
</div>
</section>
</body>
</html>
你不是真的在写会话,是吗?您应该创建另外两个方法来获取和设置实际会话中的变量。重定向后,您的消息将消失,因为它只在脚本执行时保存。
function set_notification($message) {
$_SESSION['notification'] = $message; }
function get_notification() {
if(!empty($_SESSION['notification'])) {
return $_SESSION['notification']; }
像这样:)
当然,要使会话工作,您应该在脚本的开头执行session_start()调用。点击这里了解更多信息
HTTP本质上是无共享的,因此您在一个请求中所做的任何操作对任何其他请求都不可用。您将需要使用共享数据存储来持久化这些消息。
数据库,memcache,甚至是服务器上的文本文件(假设您在单个服务器上操作,而不是在多个服务器上进行负载平衡)都是可以选择的。
您可以在客户端使用cookie来持久化少量数据。但请记住,这不是一个安全的解决方案(不使用加密),你可以在cookie中存储的数据量是有限的。
HTTP和PHP是无状态的。您需要使用会话变量来跟踪跨会话的数据
http://www.php.net/manual/en/book.session.php