What are the benefits and drawbacks of using inheritance versus composition when working with database connections in PHP classes?
When working with database connections in PHP classes, using composition is generally preferred over inheritance. Composition allows for better code organization, flexibility, and reusability compared to inheritance. Inheritance can lead to tight coupling between classes and can make the code harder to maintain and extend.
// Using composition to handle database connections in PHP classes
class DatabaseConnection {
private $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);
}
public function close() {
$this->connection->close();
}
}
class User {
private $db;
public function __construct(DatabaseConnection $db) {
$this->db = $db;
}
public function getUsers() {
$result = $this->db->query("SELECT * FROM users");
// Process the result
return $result;
}
}
// Usage
$db = new DatabaseConnection('localhost', 'username', 'password', 'database');
$user = new User($db);
$users = $user->getUsers();