2012-07-31 18:32 阅读 33


I have a mySQL Object in a class, which is in an external file (to access it from several other files). How can I get my Singleton Object from my file dbconnection.php:

class DBConnection {

  private static $instance;

  private function __construct() {
    @mysql_select_db($database) or die( "Unable to select database");  

  public function __destruct() {

  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\"";
    while ($row = mysql_fetch_object($result)) {
        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\"";

    while ($row = mysql_fetch_object($result)) {
        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))";

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanma8207 duanma8207 2012-07-31 18:35

    You need to include() or require() the file first:

    require( 'dbconnection.php');

    Then you can do:

    $db = DBConnection::getInstance();
    点赞 评论 复制链接分享