Object Oriented PHP

Hello all you Object Oriented people. I’m brand new to OO programming and had a quick question. I’m reading books, manuals, etc so please don’t tell me to RTFM, I’m on it. I’m just curios about the right way to do the following:

I want to make a class that creates a PDO mysql connection, then that same class can handle queries. So, based on a class I saw somewhere I wrote this:

class connect {
	public $mysql;
  	private $db_host = 'localhost'; //
  	private $db_username = 'user'; //Your username
  	private $db_password = 'password'; //Your password
  	private $db_name = 'db'; // Database Name
  	function __construct(){
		//Start the Connection
//		$this->mysql = new mysqli($this->db_host, $this->db_username, $this->db_password, $this->db_name) or die(mysql_error());
		$dbh = $this->mysql = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_username, $this->db_password, array(PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
  	function query($sql) {
  		$res = $this->dbh->query($sql);
  		return $res;
  	function __destruct(){
	  	//Close the Connection
	    $this->mysql = null;

But I get the following error:
Call to a member function query() on a non-object in [line that says $res =…]

Now I realize that I have not created a new object of that class and that’s why I get the error, but I’m wondering how to do this or if it’s even possible in one class, etc.


$dbh only exists within __construct(). You need to set it as a property of the object ($this->dbh) if you want to access it in other methods.

How do I do that?

$this->dbh = $this->mysql = new PDO(...);

OOP best thing to learn IMO!!!

how u gonna assign ur db info

 function __construct($dbname, $dbhost, $dbusr, $pass){ 

you could do it that way

new DB (‘db’, ‘host’, ‘isr’, pass);