|
-
Mar 15th, 2009, 02:09 AM
#1
Thread Starter
Hyperactive Member
Singleton with PHP
I have the following class:
Code:
<?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?
-
Mar 15th, 2009, 05:37 AM
#2
Re: Singleton with PHP
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?
-
Mar 15th, 2009, 05:01 PM
#3
Thread Starter
Hyperactive Member
Re: Singleton with PHP
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.
-
Mar 15th, 2009, 05:08 PM
#4
Re: Singleton with PHP
Use require_once instead. It will ensure the class is only declared once; even if the file is included more than once.
-
Mar 15th, 2009, 06:33 PM
#5
Thread Starter
Hyperactive Member
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|