GameCharmer
GameCharmer

Reputation: 633

Does duplicating the PDO object create multiple connections?

I have a question about using PDO that I haven't been able to find an answer to. This probably works the same for mysql/mysqli connections as well.

In the main include of my project, I create a PDO object using

$pdo = new PDO('connection here');

Well, I have a class that needs access to the database. So, instead of using "global $pdo;" inside of every function, I did the following.

class MyClass(){
    private $db = null;
    __construct(){
        global $pdo;
        $this->db = $pdo;
    }
    function example(){
        $sql = 'A Query';
        $this->db->prepare($sql);
    }
 }

Anyway, my question is, does doing this create 2 connections to the database since I'm effectively duplicating $pdo by setting the class' $db var equal to it? The main reason I ask is because I see this happening a lot in our system and am concerned with creating too many connections to MySQL and freaking the system out due to unnecessary connections.

As a part two, does the following cause duplication, and can I pass by ref? I'm a bit afraid to try it and cause something to break.

Change

function MyFunction($member_id, $pdo){
    //do something.
}

To

function MyFunction($member_id, &$pdo){
   //do something
}

Thanks!

Upvotes: 4

Views: 951

Answers (2)

user1843951
user1843951

Reputation: 41

It will not create two connections.To confirm you can use : xdebug_debug_zval.Check the php manual for usage. You can check the result with the helkp of below code : xdebug_debug_zval('pdo'); and xdebug_debug_zval('db');

Upvotes: 0

IMSoP
IMSoP

Reputation: 97688

As mentioned by deceze in comments, you are not actually duplicating the PDO object in this code, you are just assigning an extra variable to reference the same object.

This answer explains in detail, but to summarise, objects have an extra level of indirection - even if you don't pass by reference, you are still only copying a pointer to the object, not the object itself.

Passing by reference is only necessary if you actually want to modify the variable and have the modifications propagate back; assigning a completely new object to $pdo inside the function would be considered modifying the variable, but manipulating the object would not.

Counter-intuitively, assigning by reference is often worse for performance, as it defeats "copy on write" optimisations in the PHP engine which let separate variables with the same value share the same memory.

Upvotes: 3

Related Questions