我在學習PhP和SQL時只是構建一個小應用程序。現在,我被困在讓我的一個類的實例化被保留下來,而不必在每次頁面加載時都保持實例化。我有兩個表Users
和Representatives
。登錄函數找出他們的表並記錄它們,然後創建該類的新實例。當構建這個類時,它會執行一些操作並將它們重定向到適當的模塊。看起來我能夠實例化類,但是第二個我更改爲新文件,$current_user
變爲空。我不想保持恢復它,因爲最終在__construct()
我想存儲一些用戶信息作爲私有變量,所以我只想安置$current_user
一次,並在整個項目中使用它。再次,這種新的,所以我希望我措辭這個正確的。現在我只有Administrator
這個課程建成了(但我現在只是爲了解決這個問題而建立的)。這裏是我的課程和登錄功能所在的地方(我的所有網頁上這個文件是require_once()
)。PHP - 在整個目錄中保留類的實例化
require_once('functions.php');
// Define Database Constants
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "root");
define("DB_NAME", "livelab");
if(empty($current_user)){
$current_user;
}
function login_user($username, $password){
global $current_user;
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$sql="SELECT 'Users' AS tableName, userId as id, username as username, password as password FROM Users WHERE username='{$username}' UNION SELECT 'Representatives' as tableName, repId as id, username as username, password as password FROM Representatives WHERE username='{$username}'";
$result = mysqli_query($connection, $sql);
$user = mysqli_fetch_array($result);
if(!$user){
header('Location:' . './index.php');
}else{
if($password == $user["password"]){
mysqli_close($connection);
switch($user["tableName"]) {
case 'Users':
$current_user = new Administrator();
break;
case 'Representatives':
$current_user = new Representative();
break;
}
}
}
}
class Administrator{
private $connection;
private $user_table = 'Users';
private $user_id = 2; // I have this as a set value for test purposes right now
private $module = './mod-administrator/';
private $current_cookie;
//public vars
public $test = "hello world";
function __construct(){
$this->open_connection();
if(!session_id()) : session_start(); endif;
$this->current_cookie = mysqli_real_escape_string($this->connection, hash_password(uniqid()));
setcookie('login_token', $this->current_cookie, time() + 60, "/");
mysqli_query($this->connection, "UPDATE " . $this->user_table . " SET cookieHash='" . $this->current_cookie . "' WHERE userId='" . $this->user_id . "'");
header('Location:' . $this->module);
}
// The function that opens our connection to our DB
private function open_connection(){
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") ");
}
}
}
每個*請求*是獨立處理的;當你「改變文件」(即加載*新的URL *)時,以前的所有狀態都消失了。 – deceze
您可以在SESSION中的請求之間維護數據;如果你有類中的db連接資源之類的東西,這些不能被維護,並且需要重新建立每個請求 –
或使用像Symfony這樣的框架並將你的類聲明爲服務。 – DevDonkey