You could use a static variable to assign the Database class to and then use a if statement to check whether that variable has been instantiated.
There are many ways of doing this, but this is how I would do.
Database.php
public class Database
{
private static $instance;
private function __construct()
{
try {
// PDO Here
print("Connected!");
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance()
{
// Check is $_instance has been set
if(!isset(self::$instance))
{
// Creates sets object to instance
self::$instance = new Database();
}
// Returns the instance
return self::$instance;
}
}
index.php
Database::getInstance();
Database::getInstance();
Will only print "Connected!" once because the instance variable has been instantiated.
I recommend you to read Singleton Pattern if you haven't heard of it. Look at the example codes they show, its not in PHP but it should be easy to understand.
EDIT:
In case you want to make thegetInstance
function short you can do the following.
return !isset(self::$instance) ? self::$instance = new self : self::$instance;