0

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 
2
  • It seems to me that you are correct, and this wouldn't follow the Singleton pattern - quite confusing... I'd like to see if anyone disagrees. As for $array_object[] = $added_item, it just adds $added_item to the next available index of the $array_object array ;) Though if you're interested in where you can find out similar stuff, I usually just check php.net/manual/en Commented Jul 19, 2013 at 0:24
  • Also, if you put static $db = null; outside of the get() method, I think that would work just fine as it's only set to null the once. Maybe that's what you meant? Commented Jul 19, 2013 at 0:25

1 Answer 1

1

Try this inside your class:

private static $db; public static function get(){ if(!self::$db){ self::$db = new DatabaseConnection(); } return self::$db; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I think this should work for singleton, just wonder the case that show on the example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.