2

我在一个类中有一个 mySQL 对象,它位于一个外部文件中(从其他几个文件中访问它)。如何从我的文件dbconnection.php 中获取我的 Singleton 对象:

<?php
class DBConnection {

  private static $instance;

  private function __construct() {
    $user="root";
    $password="";
    $database="klb";
    mysql_connect("localhost",$user,$password);
    @mysql_select_db($database) or die( "Unable to select database");  
 }

  public function __destruct() {
      mysql_close();
 }

  public static function getInstance() {

    if(!self::$instance) {
      self::$instance = new self();
    }

    return self::$instance;
  }

  public function getNaviForCategory($category) {
    $query="SELECT * FROM projects WHERE category=\"$category\"";
    $result=mysql_query($query);
    $num=mysql_numrows($result);
    while ($row = mysql_fetch_object($result)) {
        $title=$row->title;
        $id=$row->id;
        echo "<div class=\"sublink\" data-subsite=\"$id\" data-category=\"$category\" data-title=\"$title\" ><a href=\"#\">$title<br />";
    }
  }

 public function getInfosForProject($id) {
    $query="SELECT * FROM projects WHERE id=\"$id\"";
    $result=mysql_query($query);
    $num=mysql_numrows($result);

    while ($row = mysql_fetch_object($result)) {
        $infos=$row->info;
        echo $infos;
    }
  } 

   private function createTableProjects(){
        $query="CREATE TABLE projects (id int(6) NOT NULL auto_increment,category varchar(30) NOT NULL,title varchar(30) NOT NULL,
        info varchar(200) NOT NULL,text varchar(8000) NOT NULL,PRIMARY KEY (id),UNIQUE id (id))";
        mysql_query($query);
   }
}

?>
4

1 回答 1

3

您需要先include()require()文件:

require( 'dbconnection.php');

然后你可以这样做:

$db = DBConnection::getInstance();
于 2012-07-31T18:35:28.977 回答