我是Php OOP的新手,已经编写了一些使用Php OOP将某些产品存储在数据库中的代码。我正在字符串中将我的用户名和密码存储在数据库类的会话变量中。这是我的数据库类的代码,以及我的登录表单的代码。当我运行它时,我得到了以下错误。
分析错误:语法错误,在第9行C:''examplep''htdocs''wdv341''php-oop-crud-level-3''config''database.php中出现意外的"$_SESSION"(T_VARIABLE)
database.php
<?php
class Database{
// specify your own database credentials
private $host = "localhost";
private $db_name = "wdv341";
private $username = $_SESSION['username'];
private $password = $_SESSION['password'];
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
userLogin.php
<?php
session_cache_limiter('none'); //This prevents a Chrome error when using the back button to return to this page.
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) //This is a valid user. Show them the Administrator Page
{
$_SESSION['username']=$_POST['username']; //pull the username from the form
$_SESSION['password']=$_POST['password'];
//var_dump($_SESSION);
include_once 'config/database.php';
if (isset($_SESSION['username']) && ($_SESSION['password'])){
header("location:read_categories.php");
}
else
{
?>
<html>
<body>
<h2>Please login to the Administrator System</h2>
<form method="post" name="loginForm" action="userLogin.php" >
<p>Username: <input name="username" type="text" /></p>
<p>Password: <input name="password" type="password" /></p>
<p><input name="submitLogin" value="Login" type="submit" /> <input name="" type="reset" /> </p>
</form>
</body>
</html>
<?php
}
?>
请帮忙!!
这个错误意味着它在第9行遇到了$_SESSION[]
,我假设它大致在这里:
private $username = $_SESSION['username'];
此时不能引用$_SESSION
。来自文档:
此声明可能包括一个初始化,但此初始化必须是一个常数值——也就是说,它必须能够在编译时进行求值,并且必须不依赖于运行时信息才能进行求值。
当创建类的实例时,您可以使用构造函数来设置该值:
class Database {
private $username;
public function __construct() {
$this->username = $_SESSION['username'];
}
}