簡體   English   中英

PHP的PDO連接范圍

[英]php pdo connection scope

大家好,我為pdo找到了一個連接類。 我在包含文件的頁面上調用連接方法。 問題是,即使我聲明該方法是公共的,在函數內部也未定義$ conn變量,我想知道是否有人在每個函數中都使用了global之后才有了一個優雅的解決方案。 任何建議,不勝感激。

連接

class PDOConnectionFactory{
    // receives the connection
    public $con = null;
    // swich database?
    public $dbType  = "mysql";

    // connection parameters
    // when it will not be necessary leaves blank only with the double quotations marks ""
    public $host    = "localhost";
    public $user    = "user";
    public $senha   = "password";
    public $db  = "database";

    // arrow the persistence of the connection
    public $persistent = false;

    // new PDOConnectionFactory( true ) <--- persistent connection
    // new PDOConnectionFactory()       <--- no persistent connection
    public function PDOConnectionFactory( $persistent=false ){
        // it verifies the persistence of the connection
        if( $persistent != false){ $this->persistent = true; }
    }

    public function getConnection(){
            try{
                // it carries through the connection
                $this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha, 
                array( PDO::ATTR_PERSISTENT => $this->persistent ) );
                // carried through successfully, it returns connected
                return $this->con;
            // in case that an error occurs, it returns the error;
            }catch ( PDOException $ex ){  echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }

    }

    // close connection
    public function Close(){
        if( $this->con != null )
            $this->con = null;
    }

}

使用的頁面

include("includes/connection.php");

$db = new PDOConnectionFactory();
$conn = $db->getConnection();

function test(){
try{
    $sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();

}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();

您可以在攜帶conn pdo類的位置聲明數據庫類,然后不必重復這些實例的實例。 以及您可以通過此類進行的所有數據庫操作。 我的意思是我的答案是您要搜索的內容。

但是我知道,您在Product Factory模式中僅使用PDO hadle類。 當您不想使用許多數據庫連接器引擎時,可以在PDO下使用常規的完整數據庫支持類(包括從一個函數執行查詢),而無需使用這種設計模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM