简体   繁体   中英

How to access PDO database connection object in another class in php?

I am using PDO in my project, So My PDO connection with database was made successfully but when I access the PDO object in another class system encountered error like following

Catchable fatal error: Object of class PDO could not be converted to string

Following is my database connection class

class DBConnect
{
    public static function getDB()
    {

        try {

                $dsn    = DTConfig::dbtype.":host=".DTConfig::host.";dbname=".DTConfig::db;
                $user   = DTConfig::user;
                $dbname = DTConfig::password;

                $db = new PDO($dsn,$user,$dbname);
                $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch(PDOException $e) {

            echo 'ERROR: ' . $e->getMessage();

        }   

        return $db;     
    }
}

In following code I want to access the PDO object but I got error like "Object of class PDO could not be converted to string on line 5"

class Administrator{

    function __construct(){

         $db = DBConnect::getDB(); //line 5 - This is not working 
         //echo $db;die;
    }

Anybody please suggest me answer Thanks in advance

I just tried it, when I try to echo the PDO object I get the same error.

Replace

echo $db;

with:

var_dump($db);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM