In JSP, if I want to connect to the database, I would create a Java class called DBManager with the following code:

```
public class DBManager {
    private final static String DB_URL = "jdbc:mysql://localhost:3306/mydb";
    private final static String DB_USERNAME = "root";
    private final static String DB_PASSWORD = "root";
    public static Connection conn = null;
    private static Statement stmt = null;

    /**
     * Tests connection with the database by getting connection using the
     * database url and username and password. And creates a dumb statement and
     * closes it to make sure everything is working fine.
     */
     static {
         try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager
                .getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
            stmt = conn.createStatement();
            stmt.close();
         } catch (Exception e) {
            e.printStackTrace();
         }
     }
}

```

Now, I can easily do something like:

```
PreparedStatement pstmt = DBManager.conn.prepareStatement("SELECT * FROM USER");

```

I'm learning PHP on my own and "most" of the online tutorials actually don't teach how to do stuff the right way.

They all do it in the traditional way in each page they need a connection:

```
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

```

Which is wrong because say you want to change your password? Then, you have to change it in each and every page that you used that password.

My question: how can I do something equivalent/similar to that Java class in PHP?

EDIT:

```
<?php 
class DBManager {
   public static $conn = null;
   private static $hostname = "localhost";
   private static $username = "root";
   private static $password = "root";
   private static $dbname = "tutorme";

   protected function __construct() {
       try {
           DBManager::$conn = new PDO("mysql:host=localhost;dbname=tutorme", DBManager::$username, DBManager::$password);
           DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
    }

    public static function getInstance() {
        if (null === DBManager::$conn) {
            DBManager::$conn = new DBManager();
        }
       return DBManager::$conn;
   }
}
?>

```

I searched a little and came up with the above code. However, now when I call 

```
$stmt = DBManager::getInstance()->prepare("INSERT INTO SUBJECT (SubjectTitle, SubjectName) VALUES (:subject,:subj)");

```

I get an error that there's no function in `DBManager` called `prepare()`

which means that my `DBManager::getInstance` is returning a `DBManager object` instead of `PDO conn object`