Link to home
Avatar of rgb192
rgb192Flag for United States of America

asked on

self instance object oriented code

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;
    }
  }

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

This appears to be an example of a Singleton, which is often used for data base connections
http://en.wikipedia.org/wiki/Singleton_pattern

Not everyone thinks the Singleton is a good idea.
http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons

In singletons, you often find a private constructor to prevent instantiation of the class.  Apparently not so, here.  The point of the design is to make sure that there is never more than one data base connection.

// THIS FUNCTION IS PUBLIC, AND STATIC, MEANING THAT IT CAN BE 
// CALLED WITHOUT INSTANTIATION OF THE CLASS
public static function getInstance(){

    // IF THERE IS NO $_instance VARIABLE
    if (!self::$_instance){
      // CREATE A NEW $_instance VARIABLE FROM THIS CLASS CONSTRUCTOR
      self::$_instance= new self();
    }
    // RETURN THE NEWLY CREATED $_instance OR THE OLD ONE THAT EXISTED BEFORE
    return self::$_instance;
}

Open in new window

SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
ASKER CERTIFIED SOLUTION
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of rgb192

ASKER

Thank you for the singleton explanation.