2016-08-13 47 views
0

下面是數據庫連接的代碼。 &下面有更多的方法。
爲了保持簡單,我決定爲其他方法創建一個單獨的類。所以無論如何,我可以在實例化其他類時連接到數據庫。
db.php中OOP使用其他類的數據庫連接

class Db{ 
private static $_instance = null; 
private $_db; 

private function __construct(){ 
    try{ 
     $this->_db = new PDO('mysql:host = localhost;dbname=db_xoo', 'root', ''); 
    } 
    catch(PDOException $e){ 
     die($e->getMessage()); 
    } 
} 

public static function get_instance(){ 
    if(!isset(self::$_instance)){ 
     return self::$_instance = new Db();  
    } 
    else{ 
     return self::$_instance; 
    } 
} 

Other.php

<?php 
class Other{ 
    . 
    . 
    . 
    public function blah(){ 
     database queries.. 
    } 
    . 
    . 
} 
?> 

現在,當我實例化類我other.What應other.php所以加,它可以對數據庫,而不是自動連接在創建之前每次調用Db::get_instance()$test = new Other()

回答

0

use cons道在其他類

這樣

class Other{ 
    private $_db; 

    private function __construct(){ 
     $this->_db = Db::get_instance(); 
    } 
    public function blah(){ 
     database queries.. $this->_db->query() 
    } 
    . 
    . 
} 
+0

好了,但如果我想在other.php使用靜態方法。它如何連接到數據庫? –

+0

使用'$ _db'連接到其他類的數據庫 – ashkufaraz

相關問題