2016-12-24 8 views
0

を閉じることができますは、どのように私は私が(グーグルによって発見)シングルトンデータベース接続クラス - をdb.phpを持って拡張したクラスからの接続

<?php 
class ext extends db { 
private $conn; 
function __construct(){ 
$this->connect(); 
if(isset($this->conn)){ 
     echo 'Connection is established<br />'; 
    } 
$this->closeConn(); 
} 
public function connect(){ 
    $this->conn = parent::getInstance()->getConnection(); 
} 
public function closeConn(){ 
    parent::closeConnection(); 
} 
} 
?> 

と私のindex.phpページでは:このよう

<?php 
spl_autoload_register(function ($class) { 
    include '../classes/' . $class . '.php'; 
}); 
$test = new ext(); 
?> 

今、私の出力は以下の通りです:

Connection is established 
Fatal error: Call to a member function close() on a non-object in (line number) of db.php 

私の質問はどうすれば拡張クラス(ext.php)で接続を閉じることができますか?

答えて

1

ソリューションは次のようになります:

  • まず、このように、extクラスの親クラスdbprivateインスタンス変数を作成します。

    class ext extends db { 
        ... 
        private $parentInstance; 
        ... 
    } 
    
  • そして、このインスタンス変数を使用します接続を作成して閉じるには$parentInstanceを入力してください。

    class ext extends db { 
        private $conn; 
        private $parentInstance; 
        function __construct(){ 
         $this->connect(); 
         if(isset($this->conn)){ 
          echo 'Connection is established<br />'; 
         } 
         $this->closeConn(); 
        } 
        public function connect(){ 
         $this->parentInstance = parent::getInstance(); 
         $this->conn = $this->parentInstance->getConnection(); 
        } 
        public function closeConn(){ 
         $this->parentInstance->closeConnection(); 
        } 
    } 
    

追記dbクラス内の1つの小さな構文エラーにもあります。コンストラクターメソッドの閉じ括弧がありません。

+0

あなたの回答に関連して、別のクラス(例えば、dbクラスを拡張する2つのクラスがあります)からdbクラスを拡張すると、関連する質問が1つ発生します。 –

+0

@ AbdullahMamun-Ur-Rashidあなたはシングルトンパターンとして 'db'クラスを実装していますので、**このクラスのインスタンスは**ただ一つあります**他の2つのクラス間で共有されます。だから問題はない。一つの小さな注意点は、親インスタンスを作成し、 'ext'クラスの' connect() 'メソッドに代入するのではなく、コンストラクタメソッドでもこれを行うことができるということです。それは何の違いもありません。 –

+0

ありがとうございました –

関連する問題