...

View Full Version : Private constructor (singleton)



marf
03-19-2007, 05:13 PM
I am trying to make a class just for connecting to the MySQL and I want to make it a singleton because only one connection should ever be needed at a time.

Heres what I have (a simplified version)



$host="myhost";
$database="mydb";
$user="myusername";
$pass="mypass";

class mysqlcon{

private static $instance = NULL;

private function __construct($host, $user, $pass){
//Construct stuff here
}

static public function getInstance($host, $user, $pass){
// getInstance stuff here
}

}

$con = new mysqlcon::getInstance($host, $user, $pass);




However when I do that last line to create the instance of the object, I get

Fatal error: Call to private mysqlcon::__construct() from invalid context

So I just want to know how I Can call the singleton class properly?

marf
03-19-2007, 06:55 PM
I figured it out with a little searching around.


If anybody wants to know for the future,
when you call the class you don't need new ClassName, because you only want one instance of the class to begin with.

so the working code for me was


$con = mysqlcon::getInstance($host, $user, $pass);

enjoy!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum