Try the following:
class DB extends PDO { protected $db_name = "PDO"; protected $db_user = "root"; protected $db_pass = "root"; protected $db_host = "localhost"; public function __construct() { try { parent::__construct("mysql:host={$this->db_host};dbname={$this->db_name}", $this->db_user, $this->db_pass); } catch (PDOException $e) { echo $e->getMessage(); } } } $db = new DB; $db->query('SELECT * FROM something');
In addition, I added the $this in front of your members because $db_name and such were not declared in the method scope.
If you do not want the connection to be initiated when the object is created, you can do the following:
class DB extends PDO { protected $db_name = "PDO"; protected $db_user = "root"; protected $db_pass = "root"; protected $db_host = "localhost"; public function __construct() { // do nothing } public function connect() { try { parent::__construct("mysql:host={$this->db_host};dbname={$this->db_name}", $this->db_user, $this->db_pass); } catch (PDOException $e) { echo $e->getMessage(); } } } $db = new DB; $db->connect(); $db->query('SELECT * FROM something');
Important Note: Usually when redefining methods in children, you need to specify the same method signature as the parent (or you will get an E_STRICT error). Fortunately, this does not apply to the main classes, perhaps in order to allow such overrides.
source share