How can PHP programs efficiently handle database connections across multiple function calls?

When handling database connections across multiple function calls in PHP, it is important to establish a single database connection object and reuse it throughout the program to avoid unnecessary overhead of opening and closing connections repeatedly. One way to achieve this is by using a design pattern like Singleton to ensure only one instance of the database connection object exists and is shared across different functions.

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
$database = Database::getInstance();
$connection = $database->getConnection();
// Use $connection to perform database operations