1

DBCONNECTbooknewの3 つのクラスを検討してください。

class dbconnect {
    protected $db_conn;
    public $db_user='xxxx';
    public $db_pass='xxxx';
    public $db_host='localhost';
    public $db_name='xxxx';

function connect() {
        try{
            $this->db_conn=new PDO("mysql:host=$this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
            return $this->db_conn;
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }
}


include_once ( 'class.dbconn.php' );

class Book{
    public $link;

    public function __construct(){
        $db_conn=new dbconnect();
        $this->link = $db_conn->connect();
        return $this->link;
    }
}

class new{
include_once 'classes/class.book.php';
$book = new Book();
}

コードにエラーはありませんでしたが、データベースへの接続を閉じることに疑いがあります。接続を閉じることは必須ですか? 必須の場合、接続を閉じるにはどうすればよいですか?どのクラスでコードを記述する必要がありますか?

4

2 に答える 2

0

手動で接続を閉じる必要はありません。PHPはそれを独自に処理します。手動で閉じたい場合は、使用できます$this->db_conn = null;

public function disconnect() {
    $this->db_conn = null
}

完璧主義者になりたい場合は、これを行うこともできますが、必須ではありません

public function __destruct() {
    $this->disconnect();
}
于 2013-09-21T05:40:06.220 に答える
0

あなたの新しいコード

<?php
class dbconnect {
    protected $db_conn;
    public $db_user='xxxx';
    public $db_pass='xxxx';
    public $db_host='localhost';
    public $db_name='xxxx';

function connect() {
        try{
            $this->db_conn=new PDO("mysql:host=$this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
            return $this->db_conn;
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

function disconnect()
    {
            try
            {
                $this->db_conn=null;
                return $this->db_conn;
            }
            catch (Exception $e){
                return $e->getMessage();
            }
            }
    }
}


include_once ( 'class.dbconn.php' );

class Book{
    public $link;

    public function __construct(){
        $db_conn=new dbconnect();
        $this->link = $db_conn->connect();
        return $this->link;
    }
}

class new{
include_once 'classes/class.book.php';
$book = new Book();

$close = new dbconnect();
// this will close connection
$close->disconnect();


}?>

もう1つ、コンストラクタとデストラクタを作成できます。

于 2013-09-21T05:57:40.903 に答える