Why is using DB::getInstance() considered bad practice in PHP?

Using DB::getInstance() is considered bad practice in PHP because it tightly couples your code to a specific implementation of the database connection, making it harder to change or test. Instead, it's better to use dependency injection to pass the database connection instance into your classes where it's needed. This allows for better flexibility, testability, and maintainability in your code.

class YourClass {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function yourMethod() {
        // Use $this->db to interact with the database
    }
}

$db = new Database();
$yourClass = new YourClass($db);
$yourClass->yourMethod();