In object-oriented programming, what are the advantages of using a singleton pattern for managing database connections across multiple classes?

When managing database connections across multiple classes in object-oriented programming, using a singleton pattern ensures that only one instance of the database connection object is created and shared among all classes. This helps in reducing resource consumption and ensures that all classes interact with the same database connection, preventing issues such as multiple connections being opened concurrently.

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

    private function __construct() {
        $this->connection = new PDO('mysql:host=localhost;dbname=my_database', '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 get the database connection instance
$database = Database::getInstance();
$connection = $database->getConnection();