What are some best practices for establishing database connections in PHP classes to avoid redundancies?

When establishing database connections in PHP classes, it's important to avoid redundancies by utilizing a singleton pattern. This ensures that only one instance of the database connection is created and reused throughout the application, preventing unnecessary 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 self();
        }
        return self::$instance;
    }

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

// Example of how to use the singleton pattern to establish a database connection
$database = Database::getInstance();
$connection = $database->getConnection();