简体   繁体   中英

How can I create an object from an external file in 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);
   }
}

?>

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

require( 'dbconnection.php');

Then you can do:

$db = DBConnection::getInstance();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM