I am quite familiar with PHP but I have just started doing a bit of object oriented stuff with it. I wanted to make a singleton database connection but I ran into a problem and error.”Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 523800 bytes) in”
I know that I am not supposed to run out of memory the query I am running is
$con = getConnection();
$stmt = $con->prepare("SELECT gene_name,jgi_protein_id FROM jgi_transcriptid_proteinid_match where our_protein_id = ?");
Here is the code for the class.
class Connection
{
// Store the single instance of connection
private static $connection;
private function __construct()
{
$connection = new mysqli(HOSTNAME, DBUSER, PASSWORD, DBNAME);
if ($connection->connect_errno)
die("Failed to connect to MySQL: (" . $connection->connect_errno . ") " . $connection->connect_error);
}
public static function getInstance()
{
if (!self::$connection)
self::$connection = new Connection();
return self::$connection;
}
public function prepare($query)
{
$statement = $this->prepare($query);
return $statement;
}
}
I am using mysqli for the database stuff.
There are a couple of issues in this code:
Infinite recursion
Referencing a local variable, instead of the static one
The code should probably reference
self::$connection. Based on the class, though, I’m not sure, asself::$connectionis used in a different way ingetInstance(), which I don’t see called anywhere.Naming confusion
The class is called
Connection, and it contains a static variable named$connection, which stores the singleton instance of the class. The constructor contains another$connection, which is instead a mysqli connection.Refactored class – UNTESTED FIX
The class below has not been tested and is provided for illustrative purpose. Use at your own risk.
class Connection {
// Store the single instance of the class
private static $instance;
// Store the mysqli connection
private $connection;
}