What are the advantages and disadvantages of using setters in PHP classes for handling database connections?
Using setters in PHP classes for handling database connections can provide flexibility and encapsulation by allowing the connection details to be easily changed or updated. However, it can also introduce complexity and potential security risks if not implemented properly, as it exposes the database connection details to external manipulation.
class DatabaseConnection {
private $host;
private $username;
private $password;
private $dbname;
public function setConnectionDetails($host, $username, $password, $dbname) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
}
public function connect() {
$conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
return $conn;
}
}
// Example usage
$db = new DatabaseConnection();
$db->setConnectionDetails('localhost', 'username', 'password', 'dbname');
$conn = $db->connect();