class Database { private static $conn = null; public static function getConnection() { if (self::$conn === null) { self::$conn = new mysqli("localhost", "username", "password", "dbname"); if (self::$conn->connect_error) { die("Connection failed: " . self::$conn->connect_error); } } return self::$conn; } } // Usage: $conn = Database::getConnection();
class Database { private static $conn = null; public static function getConnection() { if (self::$conn === null) { self::$conn = new PDO("mysql:host=localhost;dbname=db;charset=utf8", "username", "password"); self::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return self::$conn; } } // Usage: $conn = Database::getConnection();In this example, we create a `Database` class with a static `$conn` property that stores the PDO connection. The `getConnection()` method checks if the connection has already been established, and if not, creates a new PDO connection. We also set the `ERRMODE` attribute to `EXCEPTION` to catch any database errors. Both examples use the package library of either `MySQLi` or `PDO`, which are commonly used PHP database libraries.