How can the use of static methods in PHP lead to issues with global state and coupling between different layers of an application?
Using static methods in PHP can lead to issues with global state and coupling between different layers of an application because static methods are tightly bound to a specific class and can make it difficult to test, maintain, and extend the codebase. To solve this issue, it is recommended to use dependency injection to pass dependencies into classes instead of relying on static methods.
class Database {
private $connection;
public function __construct(PDO $connection) {
$this->connection = $connection;
}
public function query($sql) {
return $this->connection->query($sql);
}
}
class UserService {
private $database;
public function __construct(Database $database) {
$this->database = $database;
}
public function getUserById($id) {
$result = $this->database->query("SELECT * FROM users WHERE id = $id");
// Process the result
}
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$userService = new UserService($database);
$userService->getUserById(1);