douyan2470
2012-07-31 18:32 阅读 33
已采纳

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

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:

<?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条回答 默认 最新

  • 已采纳
    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();
    
    点赞 评论 复制链接分享

相关推荐