Trying to understand and use OOP in PHP I have a class called dbcon
. I am following a tutorial in youtube which is using the protected connect()
function to connect to db. Now my question is why not connect to db in the constructor?
function __construct() {
$this->DBSERVER = "localhost"
$this->DBUSERNAME = "root"
$this->DBPASSWORD = ""
$this->DBNAME = "thedb"
$conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
can someone let me know what is the benefit or downside of this?
<?PHP
class dbcon {
private $DBSERVER;
private $DBUSERNAME;
private $DBPASSWORD;
private $DBNAME;
protected function connect(){
$this->DBSERVER = "localhost"
$this->DBUSERNAME = "root"
$this->DBPASSWORD = ""
$this->DBNAME = "thedb"
$conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
}
?>