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 alternative method could be used to achieve the desired redirection in the provided script?
- How can PHP be used to differentiate between displaying form data and linking to an uploaded file?
- In what scenarios is SQLite a suitable alternative when a traditional database is not available for PHP development?