What are some best practices for managing database connections in PHP when working with multiple classes and subclasses?

When working with multiple classes and subclasses in PHP, it is essential to efficiently manage database connections to avoid resource wastage and improve performance. One best practice is to use a singleton pattern to create a single instance of the database connection that can be shared across classes. This ensures that connections are reused rather than recreated for each class instance, reducing overhead.

class Database {
    private static $instance = null;
    private $connection;

    private function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    }

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new Database();
        }
        return self::$instance;
    }

    public function getConnection() {
        return $this->connection;
    }
}

// Example usage
$db = Database::getInstance()->getConnection();
$stmt = $db->query('SELECT * FROM users');