mang
mang

Reputation: 173

php PDO connection close scope

From the php documentation, a PDO connection exists through the lifetime of its object. So in the below code...

<?php

for($i = 0; $i < 5; $i++)
{
    myfunc();
}

function myFunc()
{
    $conn = new PDO("connectionStuff");

    //Do things
}

?>

...since $conn is only within the scope of myFunc, does the PDO connection get closed every time myFunc is finished executing? Or does it leave 5 PDO connections hanging open until the entire page is finished?

Do I have to set $conn = null at the end of myFunc, or is that unnecessary?

Upvotes: 0

Views: 188

Answers (1)

Marcel
Marcel

Reputation: 5119

Just to answer you question you asked in the comments. In modern programming it is best practice, to use dependency injection for cases like yours. Furthermore the use of a container is more practicable. In modern object orientated frameworks there 's always a service manager, which acts as a container and provides all the stuff you need.

class DiContainer {
    protected $instances = [];

    public function __construct(array $aInstances = []) {
        $this->instances = $aInstances;
    }

    public function set($sName, $oInstance) {
        if (isset($this->instances[$sName]) {
            throw new \Exception(sprintf(
                'An instance for "%s" already exists'
                $sName
            ));
        }

        $this->instances[$sName] = $oInstance;
    }

    public function get($sName) {
        if (!isset($this->instances[$sName)) {
            throw new ErrorException(sprintf(
                'No instance for "%s"',
                $sName
            ));
        }

        return $this->instances[$sName];
    }
}

This is the dependency container. You can store all instances you need for your application in it. Keep in mind, that this is a small untested examplte, which shows the benefits of dependency injection. You shouldn 't use this in a productive way, because a DI container is much more complext than this simple example.

In practice you can use it like in the following example.

// when you instanciate your application
$oContainer = new DiContainer([
    'db-connection' => new PDO(...),
]);

// in your specific class
public function doSomethingWithDatabase(DiContainer $oContainer) {
    $oDbHandle = $oContainer->get('db-connection');
    ...
}

Upvotes: 1

Related Questions