troubleshooting Question

self instance object oriented code

Avatar of rgb192
rgb192Flag for United States of America asked on
PHP
4 Comments2 Solutions624 ViewsLast Modified:
from lynda.com php object oriented tutorial

explain this code:
  public static function getInstance(){
    if (!self::$_instance){
      self::$_instance= new self();
    }
    return self::$_instance;
  }

<?php
/**
* mysqli database: only one connection is allowed
*/
class Database{
  private $_connection;
  //store the single instance
  private static $_instance;
  /**
  * get an instance of the database
  * @return Database
  * 
  */
  public static function getInstance(){
    if (!self::$_instance){
      self::$_instance= new self();
    }
    return self::$_instance;
  }
  /**
  * constructor
  */
  public function __construct(){
    $this->connection = new mysqli('localhost','user','pass','dbname');
    //error handling
    if (mysqli_connect_error()){
      trigger_error('Failed to connect to MySql: '.mysqli_connect_error(),E_USER_ERROR);
    }
    /**
    * Empty clone magic method to prevent duplication.
    */
    private function __clone(){}
    /**
    * get the mysqli connection
    */
    public function getConnection(){
      return $this->_connection;
    }
  }
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros