2011-11-07 97 views
0

我正在處理某些事情。我想在config.php中創建一個包含連接到數據庫的方法的類。在dbConnectExample.php中,實例化該類並調用該方法。我有點困惑,因爲我正在向其他編程課程學習。這是我到目前爲止;類方法和實例

<?php # Scripts 6.3 - Rectangle.php 

Class Rectangle { 

//Declare the attributes: 
public $width = 0; 
public $height = 0; 

//Method to set the dimensions. 
Function set_size($w = 0, $h = 0) { 
     $this->width = $w; 
     $this->height = $h; 
} 

//Method to calculate and return the area. 
function get_area() { 
    return ($this->width * $this->height); 
    } 

// Method to calculate and return the perimeter. 
function get_perimeter() { 
    return (($this->width + $this->height) * 2); 
    } 

    //Method to determine if the rectangle 
    //is also a square 
    function is_square() { 

    if ($this->width == $this->height) { 
    return true; //Square 
    } else { 
     return false; //Not a square 
    } 
    } 

} //End of Rectangle class. 

我知道我正在用方法創建一個類。我只是困惑地連接到你這樣的數據庫;

//Connect to the database 
$DBConnect = @new mysqli("localhost", "valerie_2shuawna", "norris"); 
if (mysqli_connect_errno()) 
     die("<p>Unable to connect to the database server.</p>" 
     . "<p>Error code " . mysqli_connect_errno() 
     . ": " . mysqli_connect_error()) . "</p>"; 
$DBName = "config.php"; 
    @$DBConnect->select_db($DBName) 
     Or die("<p>Unable to select the database.</p>" 
     . "<p>Error code " . mysqli_errno($DBConnect) 
     . ": " . mysqli_error($DBConnect)) . "</p>"; 

$DBConnect->close(); 

但我想實例化那個類並調用方法。然後假設它包含一個連接到數據庫的方法。如果有人能幫我弄清楚我做錯了什麼,或許可以解釋,所以我沒有那麼困惑,我會感激的。

+0

格式的代碼,請。我正在談論縮進。 – Tadeck

回答

2

您可以創建一個簡單的類:

// Database.php 

class Database 
{ 
    public static function getDbo($dbName) 
    { 
     $dbo = new mysqli("localhost", "user", "password"); 

     if (mysqli_connect_errno()) { 
      throw new Exception(
       "<p>Unable to connect to the database server.</p>" 
       . "<p>Error code " . mysqli_connect_errno() 
       . ": " . mysqli_connect_error()) . "</p>" 
      ); 
     } 

     if (!$dbo->select_db($dbName)) { 
      throw new Exception(
       "<p>Unable to select the database.</p>" 
       . "<p>Error code " . mysqli_errno($DBConnect) 
       . ": " . mysqli_error($DBConnect)) . "</p>" 
      ); 
     } 

     return $dbo; 
    } 
} 

// SomeFile.php 

require_once 'Database.php'; 

try { 
    $dbo = Database::getDbo(); 

    // If I made it this far then I can start querying 
    $dbo->query('SELECT stuff FROM table'); 

    // etc. 

} catch (Exception $e) { 
    die($e->getMessage()); 
} 
0

你可能想要include_once(「config.php」)。

的config.php中應包括:1)數據庫設置,如用戶名和密碼,或者可以2)取這些值和實際執行連接

通過創建一個PHP文件,其中包括的config.php開始關閉。

你應該能夠從config.php包含文件中看到「一種連接到數據庫的方法」。

確保您打電話給它。希望有所幫助! :)

而且實例類使用new關鍵字像

$square = new Square(); 
-1

在功能總結你的數據庫連接代碼,然後包裹在一個類。把這個類放在config.php中。在dbConnectExample.php中實例化該類(請參閱@jakx中的建議)。