2016-08-29 3 views
-1

私はちょうどPHPクラスを作成しました。どのように私は "成功した接続!"エコーされるのは2回ですか?私はそれを見てみようとしましたが、それがなぜ2度印刷されるのかについて頭を浮かべることはできません。PHPデータベースクラス、エコー2回

  <?php 


      include 'dbConfig.php'; 

      class dbConnect extends dbConfig 
      { 
       public $connectionString; 
       public $dataSet; 
       private $sqlQuery; 

        protected $host; 
        protected $userName; 
        protected $passWord; 
        protected $dbName; 

       function dbParams(){ 
        $this->connectionString = NULL; 
        $this->sqlQuery = NULL; 
        $this->dataSet = NULL; 
         // Creates an object that is created on the extend (dbConfig) 
         $dbParams = new dbConfig(); 

         //Sets the variables in this class to match dbConfig's 
         $this->host = $dbParams->host; 
         $this->userName = $dbParams->userName; 
         $this->passWord = $dbParams->passWord; 
         $this->dbName = $dbParams->dbName; 
         // Object no longer needed, Null the object 
         $dbParams = NULL; 
       } 

       function dbConnect(){ 
        $this ->connectionString = mysqli_connect($this->host, $this->userName, $this->passWord, $this->dbName); 

        if($this->connectionString->connect_error){ 
         echo "Connection failed"; 
        } else{ 
         echo "Successfully Connected!"; 
        } 

        return $this->connectionString; 
       } 
      } 

答えて

0

あなたが二回あなたのコンストラクタを実行しているので:

 class dbConnect extends dbConfig { 
      function dbConnect(){ 

PHPはオブジェクトの支持を得PHPの初期の時代にさかのぼるコンストラクタ・メソッドの名前、としてクラス名を使用してサポートし、彼らのBEFORE正式な__construct()バージョンも追加されました。

ですから、自動的に次に別のオブジェクトを構築し、ため、上記のあなたのオブジェクトを作成:

 $dbParams = new dbConfig(); 
+0

えーえ理にかなっている、あなたは__constructを定義していないとき、それは自動的にあなたに1つをASSINGでしょうか? – NathanK

+0

@NathanKこれはPHP4のコンストラクタメソドロジです。関数名をクラス名と同じにすると、それはコンストラクタになります。これはPHP 5で保持され、現在は[PHP 7で非推奨](http://php.net/manual/en/migration70.deprecated.php)です。コンストラクタが必要な場合は、 '__construct()'だけを使うことをお勧めします。 – Machavity

+0

本当にありません。 __construct()がない場合、単に実行されません。 'dbConnect()'メソッドを使用することで、暗黙的なコンストラクタを使用できます。それは実行されます。 __construct()がある場合、classname()のバージョンは無視されます。 –