What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex.
$conn = new PDO(...);
function getSomething()
{
global $conn;
.
.
.
}
class DB_Instance
{
private static $db;
public static function getDBO()
{
if (!self::$db)
self::$db = new PDO(...);
return self::$db;
}
}
function getSomething()
{
$conn = DB_Instance::getDBO();
.
.
.
}
If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.