Maybe this is a silly question, but I am very new to PDO and am confused. Is it possible to instantiate a PDO object in one function (open a connection to a server/db) and then close the same connection in another function? Will the functions need to be passed the object to be able to close it? I want to do this so I can create a ubiquitous site-wide function that I can call to start a connection, execute non-generic sql, and then close it with another site-wide function. How can I do this? Do I need to pass the object to these function as arguments?
Share
Yes, this is possible. I’d recommend using a constructor that initiates a connection to MySQL and a destructor that nullifies it. That way, you won’t have to manually call the function every time you want to open and close the connection. The connection will open whenever a new instance of the object is called, and when there are no further references to the object, the connection will be nullified.
It might look something like this:
You might find this reference about constructors and destructors useful: http://php.net/manual/en/language.oop5.decon.php