Can inheritance be used when working with databases in PHP?
Inheritance can be used when working with databases in PHP by creating a base database class with common methods and properties, then extending this class to create specific database classes for different databases. This allows for code reusability and organization, making it easier to manage database connections and queries.
class BaseDatabase {
protected $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function query($sql) {
return $this->connection->query($sql);
}
}
class MySQLDatabase extends BaseDatabase {
public function __construct($host, $username, $password, $database) {
parent::__construct($host, $username, $password, $database);
}
public function escapeString($string) {
return $this->connection->real_escape_string($string);
}
}
// Example of using the MySQLDatabase class
$mysql = new MySQLDatabase('localhost', 'username', 'password', 'database');
$result = $mysql->query('SELECT * FROM table');
Related Questions
- What security considerations should be taken into account when using PHP to interact with email accounts for a web application?
- How can PHP be utilized to differentiate between new and already read comments in a forum setting?
- Are there alternative methods to utf8_decode for converting special characters to their correct representations in PHP7 without affecting other characters in the text?