我刚刚创建了一个PHP类,我仍然围绕着课程以及它们如何工作。为什么我的“成功连接!”得到两次回声?我试过看过它并且无法理解为什么会打印两次。
<?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 :(得分:0)
因为您正在运行构造函数两次:
class dbConnect extends dbConfig {
function dbConnect(){
PHP支持使用类名作为构造方法的名称,这可以追溯到PHP获得对象支持的早期阶段,之前他们还添加了正式的__construct()
版本。
因此,由于上述原因,您自动构造对象,然后使用以下内容构造另一个对象:
$dbParams = new dbConfig();