You must
1) disable the designer by setting it to closed.
2) create a single PDO object by calling only the static method. The static method should return an instance of the PDO.
In Silex or Symfony, you will need to assign the class name "\" or use "use \ PDO;". This does not mean that it is a global class.
Ps. if you set the __constructor to the public and use return functino, note that it will not throw any exceptions or warnings, but you will get the returned class object, not the actual value of the return statement.
So $ db = new Database () will return an object of class Database. Then from there you will need to access the PDO using the class method. $ pdo = $ db-> getInstance () This is the wrong way to create the correct singleton.
If you are interested in learning more about the pros and cons of singleton, and for some usage examples read this Best Practices in singleton PHP classes , you will find more information about this template.
class Database { private static $_instance; private function __construct() { self::$instance = new PDO( "mysql:host=localhost;dbname=live", "root", "root" ); } public function __clone() { die(__CLASS__ . ' class cant be instantiated. Please use the method called getInstance.'); } public static function getInstance() { if(!self::$_instance instanceof PDO){ new self; } return self::$_instance; } }
Devwl source share