How does encapsulating this functionality within a class or database class impact performance and maintainability?
Encapsulating functionality within a class or database class can improve performance by organizing code into reusable components and reducing redundancy. It also enhances maintainability by promoting a modular structure that is easier to update and debug.
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
return $this->connection->query($sql);
}
public function close() {
$this->connection->close();
}
}
// Example usage
$db = new Database('localhost', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM table");
while ($row = $result->fetch_assoc()) {
// Process data
}
$db->close();
Related Questions
- Are there any specific configurations or settings that need to be checked when troubleshooting PHP-related issues on a website?
- What are the best practices for handling user input validation in PHP to prevent unauthorized data submissions?
- Are there any specific functions or methods in PHP that are particularly useful for working with CSV files?