Does a PDO object duplicate multiple connections?

I have a question about using PDO to which I could not find the answer. This probably works for mysql / mysqli connections.

In the main inclusion 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 each 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); } } 

In any case, my question is: does this make 2 connections to the database, since I effectively duplicate $ pdo by setting the $ db var class for it? The main reason I ask is because I see this happening a lot on our system, and I'm interested in creating too many MySQL connections and ridding the system of unnecessary connections.

As part two, does the next reason have duplication, and can I go through ref? I'm a little afraid to try and make something break.

Change

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

For

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

Thanks!

+4
source share
2 answers

As mentioned in the comment comments, you are not actually duplicating the PDO object in this code, you are simply assigning an additional variable to refer to the same object.

This answer explains in detail, but to summarize, objects have an additional level of indirection - even if you don't follow the link, you still only copy the pointer to the object, not the object itself.

Passing by reference is only necessary if you really want to change the variable and change it; assigning a completely new $pdo inside a function will be considered a modification of the variable, but manipulating the object will not.

Counterintuitively, link assignment is often worse for performance because it defeats copy-to-write optimization in the PHP engine, which allows individual variables with the same value to share the same memory.

+3
source

It will not create two connections. For confirmation, you can use: xdebug_debug_zval. Check the php manual for use. You can check the result using helkp below code: xdebug_debug_zval ('PDO'); and xdebug_debug_zval ('db');

0
source

Source: https://habr.com/ru/post/1484194/


All Articles