2011-11-07 52 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中的建议)。