Tim Raynor
Tim Raynor

Reputation: 753

Singleton syntax in PHP code

I understand the singleton pattern, but I don't understand the following syntax:

    public static function get()
    {
      static $db = null;
      if ( $db == null )
        $db = new DatabaseConnection();
      return $db;
    }
    private function __construct()
    {
      $dsn = 'mysql://root:password@localhost/photos';
      $this->_handle =& DB::Connect( $dsn, array() );
    }

Why every time we call DatabaseConnection::get() we could ge the same singleton object? Because the code read from me will like:

    static $db = null; //set $db object to be null
    if($db==null)  // $db is null at the moment every time because we just set it to be null
      // call the private constructor every time we call get() *
      $db = new DatabaseConnection();  
    return $db;  // return the created 

Then how the get() function could always return a same object?

I am new to Php, most of the syntax to me will read like java, please any one could explain this to me?

Also is there any instructions/tutorial that I could read for understanding more syntax sugar like:

       $array_object[] = $added_item

Upvotes: 0

Views: 92

Answers (1)

Jean Paul
Jean Paul

Reputation: 912

Try this inside your class:

private static $db;

public static function get(){
    if(!self::$db){

         self::$db = new DatabaseConnection();

     }

    return self::$db;
}

Upvotes: 1

Related Questions