What are the potential performance implications of establishing a new database connection in each class in PHP?

Establishing a new database connection in each class in PHP can lead to performance issues due to the overhead of creating and closing connections multiple times. To solve this, it is recommended to use a singleton pattern to create a single database connection instance that can be shared across all classes.

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 of how to use the singleton database connection
$db = Database::getInstance();
$connection = $db->getConnection();