Skip to content
Advertisement

Does mysqli_close() do anything other than just destroying the object?

I know that using mysqli_close() is not needed, because PHP will destruct the object when the script is finished.

What I would like to know is why do we have such a function in the language in the first place? Does it do anything else, other than just destroying the object?

Is it equivalent to $conn = null; or unset($conn);?

Having limited C knowledge I looked into the source code to see what happens when I call this method, but I can’t find anything other than just clearing internal pointers and calling efree().

Calling destructor on an object is never recommended, so why do we have a special exposed destructor for mysqli?

Advertisement

Answer

Remember that mysqli is an iteration on the mysql_* family of functions that are themselves little more than wrappers around the C Connector Library for MySQL. mysql_close is one such function, and naturally became mysqli_close in the “improved” API.

There are some situations where you’d want to force-close something immediately rather than waiting for the garbage collector to get around to it and automatically release the resource.

PDO, which is a better API all-around and doesn’t deal with MySQL exclusively, has some notes on when a connection will actually be closed:

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning NULL to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.

Tracking down those references can be annoying so it’s actually nice that mysqli has a “just close it, don’t care” function for those situations where that matters.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement