Trying to make singletone PDO with a namespace. Here is the Db connection class

namespace liw\components; class Db { private static $_db = null; private function __construct() {} private function __clone() {} private function __wakeup() {} public static function getInstance() { if (self::$_db === null) { $dsn = "mysql:host=localhost;dbname=table"; self::$_db = new PDO($dsn, 'root', ''); } return self::$_db; } } 

Attempts to access class Db in the model result in an error

Class 'liw \ components \ PDO' not found

  namespace liw\models; class Test { private $_db = null; public function __construct() { $this->_db = \liw\components\Db::getInstance(); } public function getList() { $list= array(); $result = $this->_db->query("SELECT * FROM table"); $i = 0; while ($row = $result->fetch()) { $list[$i]['id'] = $row['id']; $i++; } return $list; } } 

I understand that there is an attempt to create a PDO class that does not have a namespace. How to fix it?

  • And loading of classes for example through spl_autoload_register made? In PHP, there is no automatic pickup of classes, as in Java)) - Alexey Shimansky
  • Loading was by means of autoload composer - Misha Rodnoy
  • Those. class loading works. I in the class Test did a simple getString method that returned a string. Everything works, if not to refer to the class Db, there he cannot find a new PDO - Misha Rodnoy

1 answer 1

Having looked through Google, I came across the PDO class call.

My old:

 self::$_db = new PDO($dsn, 'root', ''); 

My new:

 self::$_db = new \PDO($dsn, 'root', ''); 

The point is in the slash.

  • Those. The PDO class is built into PHP (the interlayer) and if you use the namespace in your code, then you need to create it using the new \ PDO slash - Misha Rodnoy
  • one
    Or at the beginning of the file write use \PDO - vp_arth
  • Understood, accepted. Thank. - Misha Rodnoy