PDA

Click to See Complete Forum and Search --> : Singleton with PHP


xxarmoxx
Mar 15th, 2009, 02:09 AM
I have the following class:

<?php

// this is a singelton database connect class

class dbconnect {


// Store the single instance of Database
private static $m_pInstance;

private function __construct() {

// *** Database Connect ***
$dblink = mysql_connect('localhost', 'root', 'pwd') OR die(mysql_error());
$m_pInstance = mysql_select_db(",ydb") or die(mysql_error());


}


private function __clone() {




}




public static function getInstance()
{
if (!self::$m_pInstance)
{
self::$m_pInstance = new dbconnect();
}

return self::$m_pInstance;
}





}



?>


but I get the following error when I have muliple include statements using this class:

Fatal error: Cannot redeclare class dbconnect in


I know I need some code in the __Clone function. Im not sure what to put in there, can someone help?

visualAd
Mar 15th, 2009, 05:37 AM
A singleton is a class which can only have a single instance. Cloning the object would create multiple instances and it would therefore it would no longer be a singleton.

Why do you need to have multiple instances of the class?

xxarmoxx
Mar 15th, 2009, 05:01 PM
I see your point, maybe I am doing something wrong, but check out why its erroring.

I have one class, lets call it class A. I also have another class, lets call it class B.

Both of these classes "require 'dbconnect.php';" since they both need to connect to the database.

Now in my index.php file, I want to make instances of both A and B classes but both "require 'dbconnect.php';".

See the problem? There is no error when I either use class A alone or class B alone in index.php. It only errors when I use both at the same time.

Thanks for helping out.

visualAd
Mar 15th, 2009, 05:08 PM
Use require_once instead. It will ensure the class is only declared once; even if the file is included more than once.

xxarmoxx
Mar 15th, 2009, 06:33 PM
It works, thanks boss.