2012-10-23 65 views
2

我想創建一個數據庫類與PHP的主機作爲變量。我不能得到初始化的值堅持,我不知道爲什麼。當我初始化他們在我設置它們公開的頂部它工作正常,但是當我嘗試在構造函數中初始化它們時,它不起作用。PHP變量不存儲

class Database { 

    public $dbHost; 
    public $dbUser; 
    public $dbPass; 
    public $dbName; 

    public $db; 

    public function __construct($Host, $User, $Pass, $Name){ 
     $dbHost = $Host; 
     $dbUser = $User; 
     $dbPass = $Pass; 
     $dbName = $Name; 
     $this->dbConnect(); 
    } 

    public function dbConnect(){ 
     echo $dbPass; 
     $this->db = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName); 

     /* check connection */ 
     if (mysqli_connect_errno()){ 
      printf("Connect failed: %s\n", mysqli_connect_error()); 
      exit(); 
     }else{ 
      //echo 'connection made'; 
     } 
    } 

回答

6

你沒有在構造函數中正確初始化它們;嘗試:

$this->dbHost = $Host; 

你當前做的是初始化一個名爲$ DBHOST一個局部變量,其範圍僅僅是構造函數本身。

+0

ahh哇。我現在很累,現在正在編碼哈哈 –

2

您必須使用$this才能訪問類中的實例變量,例如$this->dbHost = $Host;

2

更改此:

public function __construct($Host, $User, $Pass, $Name){ 
     $dbHost = $Host; 
     $dbUser = $User; 
     $dbPass = $Pass; 
     $dbName = $Name; 
     $this->dbConnect(); 
    } 

這樣:

public function __construct($Host, $User, $Pass, $Name){ 
     $this->dbHost = $Host; 
     $this->dbUser = $User; 
     $this->dbPass = $Pass; 
     $this->dbName = $Name; 
     $this->dbConnect(); 
    } 
0

如何使用這個 - >

public function __construct($Host, $User, $Pass, $Name){ 
    $this->dbHost = $Host; 
    $this->dbUser = $User; 
    $this->dbPass = $Pass; 
    $this->dbName = $Name; 
    $this->dbConnect(); 
} 
1

試試這個:

public function __construct($Host, $User, $Pass, $Name){ 
     $this->dbHost = $Host; 
     $this->dbUser = $User; 
     $this->dbPass = $Pass; 
     $this->dbName = $Name; 
     $this->dbConnect(); 
    }