What are the potential pitfalls of creating a new database connection instance every time a UserManager class is instantiated?

Creating a new database connection instance every time a UserManager class is instantiated can lead to performance issues and resource wastage. It is more efficient to reuse the same connection throughout the application to avoid unnecessary overhead. To solve this, you can implement a database connection singleton pattern where the connection is established only once and then reused whenever needed.

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;
    }
}

class UserManager
{
    private $db;

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

    public function getUserById($id)
    {
        $connection = $this->db->getConnection();
        // Query database for user with given id
    }
}