How can the use of "extends" in PHP classes lead to incorrect code structure and potential issues?
Using "extends" in PHP classes can lead to issues such as tight coupling, where subclasses are highly dependent on the implementation details of the parent class. To solve this, consider using composition over inheritance. By creating separate classes that handle specific functionalities and then injecting them into the main class, you can achieve better code structure and avoid potential issues.
<?php
class DatabaseConnection {
private $connection;
public function __construct($host, $username, $password) {
$this->connection = new PDO("mysql:host=$host;dbname=myDB", $username, $password);
}
public function query($sql) {
return $this->connection->query($sql);
}
}
class UserRepository {
private $dbConnection;
public function __construct(DatabaseConnection $dbConnection) {
$this->dbConnection = $dbConnection;
}
public function getUsers() {
return $this->dbConnection->query("SELECT * FROM users");
}
}
// Usage
$dbConnection = new DatabaseConnection('localhost', 'root', 'password');
$userRepository = new UserRepository($dbConnection);
$users = $userRepository->getUsers();
?>