如何在PHP中从外部文件创建对象

时间:2012-07-31 18:32:18

标签: php file object singleton external

我在一个类中有一个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);
   }
}

?>

1 个答案:

答案 0 :(得分:3)

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

require( 'dbconnection.php');

然后你可以这样做:

$db = DBConnection::getInstance();