Q:

PHP Parent Class is a DB connection: Will multiple use due to inheritance affect performance?

I have a class that handles connections:
Class db_connect{

    private $server;
    private $username;
    private $password;
    private $database;

    protected function Connect(){
        $this->server = "localhost";
        $this->username = "root";
        $this->password = "";
        $this->database = "db_test";

        $conn = new mysqli($this->server, $this->username, $this->password, $this->database);
        return $conn;
    }
}

If I have a couple of child class that extends to this parent, will it affect the performance somehow since it is always trying to connect several times?
If so how can I possibly improve on it? Thanks.

A:

You'll connect every time you invoke that method. However, let's rewrite it a bit:
Class db_connect{

    private $server;
    private $username;
    private $password;
    private $database;
    private static $connection;

    protected function Connect() {      
        if(!(static::$connection instanceof mysqli)) {
            $this->server = "localhost";
            $this->username = "root";
            $this->password = "";
            $this->database = "db_test";

            static::$connection = new mysqli($this->server, $this->username, $this->password, $this->database);
        }

        return static::$connection;
    }
}

In the above example, there's only one connection, ever. That's why it's defined as static. Now you can call $obj->Connect(); as many times as you want, it'll be using one connection only. Others mentioned it, it's called a singleton. There are drawbacks and advantages to it, but that's outside of the scope of your question.

