Search code examples
phpconnectionpdoextend

php class extended multiple times


After spending half an hour to find a proper, self-explaining title for this question, I finally gave up. Apologies for it, I'm not a native English speaker.

Anyways, the question is about using a particular class to be extended multiple times - not multiple inheritance. So, imagine two repository classes called from the same function:

public function someFunction() 
{
   $qp = QuestionRepository();
   $cp = CommentRepository();
} 

and the QuestionRepository is like:

class QuestionRepository extends PDO 
{
    public function __construct()
    {
        parent::__construct();
    }
}

the CommentRepository is like:

class CommentRepository extends PDO 
{
    public function __construct()
    {
        parent::__construct();
    }
}

whereas the PDO class is like this:

class PDO 
{
    public function __construct() 
    {
        $pdo = new PDO(...);
    } 
}

So basically, the PDO class is extended twice, therefore two instances of PDO is initiated. However, the question is whether this means 2 different connections to mysql - which would result in performance decrease or the pdo recognizes that there is an alive connection therefore it just ignores the second instance?


Solution

  • You could declare a "static" field in PDO for the mysql connection. That way the same field will be used in each instance, regardless of which subclass is responsible for the instantiation.

    It also requires that you access the field statically; PDO::$mysql_link;

    If you declare the field without specifying visibility it will be public, meaning you'll be able to refer to the same field from anywhere as long as PDO is defined.