PHP – Objects Inside Includes

I had an interesting problem today. For some unknown reason our connections to the MySQL server were being rejected because “Too many connections” were open to it. Upon review it turns out that there were many sleeping connections. In other words, the connection was open and then never closed. Many things came to mind. An attack, a change in server hardware/software, a bug.

I traced the problem to files that were included that also had made use of my DB connection wrapper. The parent script was called, the include included which contained an instantiation of the DB connection wrapper class, and then the parent script successfully ran and terminated.

The object has a destructor which I defined to even go ahead and disconnect when the object was destroyed. Nothing extraordinary:

function __destruct()
	{
		$this->disconnect();
		
		if($this->mode == "debug") {
			printf("DESTRUCT: Successful. Class terminated\n");
		}
		
		return true;
	}

But referring to the PHP website, it seems that the disconnection should have occurred automatically.

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

It turns out, after doing some troubleshooting, that this was not occurring. I had to force a disconnect (which wasn’t a problem because the class contained a public method to do so) manually after I was finished with the DB connection. So long sleeping connections and inaccessible MySQL server.

I should also mention that in the parent file the DB wrapper class is instantiated and the destructed without the implicit called of the disconnect() method.

But the thing is, why? Why did this start occurring today at 4:00 AM PST? If it was a bug in my code like perhaps I should have known that this would happen with objects instantiated within included files then it should have happened many times over with how long this code had been up. With our parent company managing our web hosting it will be something that I may never know.

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to PHP – Objects Inside Includes