连接2个数据库

时间:2015-02-09 19:55:25

标签: php database oop

与DB的连接存在问题。

DB的使用类

class DB
{
    public static $connect = false;
    private $database_host = 'localhost';
    private $database_user = '';
    private $database_pass = '';
    private $database_db = '';
    private $database_type = 'mysql';

    function __construct($database_host, $database_db, $database_user, $database_pass)
    {
        $this->database_host   = $database_host;
        $this->database_db     = $database_db;
        $this->database_user   = $database_user;
        $this->database_pass   = $database_pass;

        if (self::$connect === false) {
            $this->connect();
        }
    }

    private function connect()
    {
        $dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;

        try {

            self::$connect = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::ATTR_PERSISTENT => false, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
            self::$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            //var_dump(self::$connect);

            if(!self::$connect) {
            die("Cannot connect to DB");    
            }


        } catch (PDOException $e) {

           die("Cannot connect to DB");

        }
    }


    }

此连接,2 DB

$connect        = new DB(_DB_HOST_, _DB_NAME_, _DB_USER_, _DB_PASS_);
$connectSlave   = new DB(_DB_HOST_, _DB_NAME_, _DB_USER_, _DB_PASS_);

首先连接 - 好,第二 - 致命错误:访问未声明的静态属性:DB :: $ connectSlave

请帮帮我。

1 个答案:

答案 0 :(得分:1)

$ connect应该是实例变量而不是静态(否则它在数据库实例之间共享):

public $connect = false;

然后使用$this->connect代替self::$connect。这是你的班级:

class DB
{
    public $connect = false;
    private $database_host = 'localhost';
    private $database_user = '';
    private $database_pass = '';
    private $database_db = '';
    private $database_type = 'mysql';

    function __construct($database_host, $database_db, $database_user, $database_pass)
    {
        $this->database_host   = $database_host;
        $this->database_db     = $database_db;
        $this->database_user   = $database_user;
        $this->database_pass   = $database_pass;

        if ($this->connect === false) {
            $this->connect();
        }
    }

    private function connect()
    {
        $dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" . $this->database_host;

        try {

            $this->connect = new PDO($dsn, $this->database_user, $this->database_pass, array(PDO::ATTR_PERSISTENT => false, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
            $this->connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            //var_dump(self::$connect);

            if(!$this->connect) {
            die("Cannot connect to DB");    
            }


        } catch (PDOException $e) {

           die("Cannot connect to DB");

        }
    }
    }