2015-12-01 107 views
0

我是Php OOP的新手,已經編寫了一些代碼,用於使用PHP OOP在數據庫中存儲某些產品。我試圖將我的用戶名和密碼存儲在我的數據庫類的會話變量中。這是我的數據庫類代碼以及我的登錄表單。我在運行時出現以下錯誤。在數據庫類中存儲變量

解析錯誤:語法錯誤,意想不到 '$ _SESSION'(T_VARIABLE)在C:\ XAMPP \ htdocs中\ wdv341 \ PHP-OOP-CRUD級-3 \設置\ database.php中在第9行

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" />&nbsp;</p> 
       </form> 
</body> 
</html> 
<?php 
} 
?> 

請幫助!

回答

1

錯誤意味着它跑進$_SESSION[]第9行,我以爲大致位置:

private $username = $_SESSION['username']; 

你不能在這一點上引用$_SESSIONFrom the docs

... This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

可以使用constructor來設置值創建類的實例時,而不是:

class Database { 
    private $username; 

    public function __construct() { 
     $this->username = $_SESSION['username']; 
    } 
} 
+0

非常感謝,這是修復! –