Reputation: 99
If I have some code like this mock example
function openDatabaseConnection() {
$pdo = new PDO();
}
openDatabaseConnection();
while (true) {
// is there still an open database connection?
}
Php and mysql will close the connection to any open database connections at the end of the script, but is a connection to the database maintained until the end of the script when the database connection is scoped to a function? During the while (true) {}
section of the code, is there still a db connection? Is it possible that php is maintaining the pointer to the DB variable as a permanent resource internally?
Upvotes: 0
Views: 45
Reputation: 57131
Although this could be closed with variable scope, I wanted to explain it a bit more for this instance.
As the $pdo
is declared inside the function, as soon as the function finishes, the variable will be un-referenced. This allows PHP to close the connection as it's no longer used.
If instead you return the connection and store this return value, this returned value is then available for use further down the script...
function openDatabaseConnection() {
$pdo = new PDO();
// Configure PDO attributes
return $pdo;
}
$pdo = openDatabaseConnection();
while (true) {
// use $pdo for database access
}
One thing to mention is that this is more about the variable scope and not the actual connection.
Upvotes: 1