Yes, You are right "it cannot be instantiated more than once." and this concept is very useful when you opening a database connection.
Suppose,
If someone logins, you make new database object.
If someone updates something, you make a new database object.
If someone logouts, you make a new database object.
As you can see, every time if there is interaction with database, a new object will be created and a new connection will be opened. That's a bad thing in term of efficiency.
Here singleton class really solves the problem. It makes a database connection object and holds it, whenever required it just returns it instead of ocreate a new one.
class DB{
private static $_instance = null;
private $_pdo;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host ='yourhost'; dbname = 'your_database','username','password);
echo 'connected';
}catch(PDOException $e){
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
}
As you can see this class checks for existing connection ($_instance attribute), and returns it if it's not been set.