Accessing a PDO instance from another class

2019-08-25 04:55发布

Here is my db class for connecting with database using pdo ext.

class db
{
    private $host;
    private $dbname;
    private $username;
    private $password;

    public function __construct($host,$db,$name,$pass)
    {
         $this->host=$host;
         $this->dbname=$db;
         $this->username=$name;
         $this->password=$pass;
         $dsn = 'mysql:'.$this->dbname.';'.$this->host;
         try 
         {
            $conn = new PDO($dsn, $this->username, $this->password);


            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         } 
         catch(PDOException $e) 
         {
              echo 'ERROR: ' . $e->getMessage();
         }
 }
}

I call db class in login class like this...

$host='localhost';
        $db='techy_issue_tracker';
        $name='root';
        $pass='';
        $base= new db($host,$db,$name,$pass);

Here is the problem, to make a pdo query inside login class (extending db class) if I use a line this...

$stmnt = $conn->prepare('SELECT id FROM users WHERE name :name OR email = :email');

It generates two errors, saying.. Notice: Undefined variable: conn... and Fatal error: Call to a member function prepare() on a non-object...

I can fix this by simply putting all pdo stuff inside login class but still I am just curious...how do you guys call an object (which is an instance of pdo class?) from another class.

PHP Class Based User System With PDO - Call to a member function prepare() on a non-object This question is interesting but didn't understand much :/

Didn't practice OOP much so some good explanation would be appreciated! Thanks.

标签: php class pdo
3条回答
Ridiculous、
2楼-- · 2019-08-25 05:00

You need to intialize $conn as a public property of your db class.

After the private properties in your db class, add this:

public $conn;

Then, inside your try catch, change $conn to $this->conn:

$this->conn = new PDO($dsn, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Then, assuming you've correctly extended the db class, you can access conn in this manner:

$stmt = $db->conn->prepare('SELECT id FROM users WHERE name :name OR email = :email');

查看更多
聊天终结者
3楼-- · 2019-08-25 05:16

There's an error in your WHERE clause:

WHERE name :name

You're missing an equal sign:

WHERE name = :name
查看更多
爷、活的狠高调
4楼-- · 2019-08-25 05:21

Why don't you just add a method to the db class that takes in a sql string and returns an array of object. Just do all the statement thingy in that method. Then the login class can just call this method to do any query. It does not need to know how the database connection is implemented. This way, if you want to change the underlying implementation in future. It only affects the db class. Not much changes is to be done to the login class as all database accesses goes through the db class.

查看更多
登录 后发表回答