473,406 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Singleton

I was just wondering something about this.

I wanted to do something similar, like having a mysql class that there can
only be one of. The purpose of this was not to have hundereds to mysql
connections open, and also to track how many queries are being sent/second.

When creating the singleton, I assume you use this syntax:

$var = &new singelton;

However, in the class, how can you check to make sure there has not been
another class created under a different var?

My way of doing it would have been to make a static var in the __construct
class, checking if this has been registered as a var or not. If no, create
class, otherwise exit class.

Would this work? Or is there a better way of doing it?

Thanks.
Jul 17 '05 #1
11 2326
> My way of doing it would have been to make a static var in the
__construct
class, checking if this has been registered as a var or not. If no,
create
class, otherwise exit class.


You can't prevent construction in constructor.

$singleton = &Class::obtainInstance();

obtainInstance should be static method, which returns existing
instance (from static var) or creates new one.

AFAIK in PHP it is not possible to make general base class for singletons
- you need to, but cannot know the name of inheriting class that uses
function of the base class.

--
* html {redirect-to: url(http://browsehappy.pl);}
Jul 17 '05 #2
On Wed, 19 Jan 2005 12:58:37 +1300, "[Mystic]" <screwuspammer> wrote:
I was just wondering something about this.

I wanted to do something similar, like having a mysql class that there can
only be one of. The purpose of this was not to have hundereds to mysql
connections open, and also to track how many queries are being sent/second.

When creating the singleton, I assume you use this syntax:

$var = &new singelton;

However, in the class, how can you check to make sure there has not been
another class created under a different var?

My way of doing it would have been to make a static var in the __construct
class, checking if this has been registered as a var or not. If no, create
class, otherwise exit class.

Would this work? Or is there a better way of doing it?


If you mean "return the previously created object" where you said "exit class"
then yes, that's pretty much the standard way of creating a singleton. In
multithreaded languages there's a bit more to it, to stop a race condition
creating two instances concurrently, but that's not a problem in PHP.

"php singleton" on Google yields some useful looking hits.

--
Andy Hassall / <an**@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Jul 17 '05 #3
On 2005-01-18, [Mystic] <screwuspammer> wrote:
I was just wondering something about this.

I wanted to do something similar, like having a mysql class that there can
only be one of. The purpose of this was not to have hundereds to mysql
connections open, and also to track how many queries are being sent/second.

When creating the singleton, I assume you use this syntax:

$var = &new singelton;

However, in the class, how can you check to make sure there has not been
another class created under a different var?

My way of doing it would have been to make a static var in the __construct
class, checking if this has been registered as a var or not. If no, create
class, otherwise exit class.

Would this work? Or is there a better way of doing it?


Only a couple of things to get you started (php5)

- make the constructor private
- make a public method getInstance that provides the static instance of
the class (if that instance == null -> call constructor...)
- override the __clone function... (might encounter a problem here.....)

--
Met vriendelijke groeten,
Tim Van Wassenhove <http://www.timvw.info>
Jul 17 '05 #4
Thanks all of you,

Very helpful information.
Jul 17 '05 #5
One last thing,

How can you call a classes function, before you have even created an object
that uses that class?

IE:

class::GetInstance();

Jul 17 '05 #6
This is what I have so far:

class database {

private function __construct($called_from_getinstance = false) {
if (!$called_from_getinstance)
echo "Fatal error has occured. Tried to recreate database() class";
}

public function &getInstane() {
static $database_object; // reference object

if (!is_object($database))
$database_object = new database(true); // create new object

return $database_object; // return address of object
}
}

$test = &database::getInstane(); // get static instance of class
?>

Can anyone see any errors in this?

Im getting the following:
Debug Strict (PHP 5): C:\Projects\ixon.co.nz\includes\classes\mysql.clas s
line 26 - Non-static method database::getInstane() should not be called
statically

Jul 17 '05 #7
On 2005-01-19, [Mystic] <screwuspammer> wrote:
[snip singleton code]

<?php
error_reporting(E_ALL);

class Singleton
{
private static $singleton;

private function __construct()
{
mysql_connect('localhost', 'timvw', 'tvw123');
mysql_select_db('timvw');
}

public static function getInstance()
{
if (self::$singleton == null)
{
self::$singleton = new Singleton;
}
return self::$singleton;
}

public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}

$singleton = Singleton::getInstance();
$evil = clone($singleton);
?>

--
Met vriendelijke groeten,
Tim Van Wassenhove <http://www.timvw.info>
Jul 17 '05 #8
On 2005-01-19, [Mystic] <screwuspammer> wrote:
This is what I have so far:

class database {

private function __construct($called_from_getinstance = false) {
if (!$called_from_getinstance)
echo "Fatal error has occured. Tried to recreate database() class";
}

public function &getInstane() {
static $database_object; // reference object

if (!is_object($database))
$database_object = new database(true); // create new object

return $database_object; // return address of object
}
}

$test = &database::getInstane(); // get static instance of class
?>

Can anyone see any errors in this?

Im getting the following:
Debug Strict (PHP 5): C:\Projects\ixon.co.nz\includes\classes\mysql.clas s
line 26 - Non-static method database::getInstane() should not be called
statically


You should make the getInstance function static.....
<?php

error_reporting(E_ALL);

class Singleton
{
private static $singleton;

private function __construct()
{
mysql_connect('localhost', 'timvw', 'xxxxxx');
mysql_select_db('timvw');
}

public static function getInstance()
{
if (self::$singleton == null)
{
self::$singleton = new Singleton;
}
return self::$singleton;
}

public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}

$singleton = Singleton::getInstance();
$evil = clone($singleton);
?>


--
Met vriendelijke groeten,
Tim Van Wassenhove <http://www.timvw.info>
Jul 17 '05 #9
NC
[Mystic] wrote:

I wanted to do something similar, like having a mysql class
that there can only be one of. The purpose of this was not
to have hundereds to mysql connections open,


Well, let's start by reading PHP documentation:

If a second call is made to mysql_connect() with the same
arguments, no new link will be established, but instead,
the link identifier of the already opened link will be
returned.

http://www.php.net/manual/en/function.mysql-connect.php

So there's no need to use singletons for this purpose. MySQL
is capable of doing it on its own.

Cheers,
NC

Jul 17 '05 #10

"Tim Van Wassenhove" <ti***@users.sourceforge.net> wrote in message
news:35*************@individual.net...
On 2005-01-19, [Mystic] <screwuspammer> wrote:
This is what I have so far:

class database {

private function __construct($called_from_getinstance = false) {
if (!$called_from_getinstance)
echo "Fatal error has occured. Tried to recreate database() class";
}

public function &getInstane() {
static $database_object; // reference object

if (!is_object($database))
$database_object = new database(true); // create new object

return $database_object; // return address of object
}
}

$test = &database::getInstane(); // get static instance of class
?>

Can anyone see any errors in this?

Im getting the following:
Debug Strict (PHP 5): C:\Projects\ixon.co.nz\includes\classes\mysql.clas s line 26 - Non-static method database::getInstane() should not be called
statically


You should make the getInstance function static.....
<?php

error_reporting(E_ALL);

class Singleton
{
private static $singleton;

private function __construct()
{
mysql_connect('localhost', 'timvw', 'xxxxxx');
mysql_select_db('timvw');
}

public static function getInstance()
{
if (self::$singleton == null)
{
self::$singleton = new Singleton;
}
return self::$singleton;
}

public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}

$singleton = Singleton::getInstance();
$evil = clone($singleton);
?>


--
Met vriendelijke groeten,
Tim Van Wassenhove <http://www.timvw.info>


Thanks heaps.
Jul 17 '05 #11

"NC" <nc@iname.com> wrote in message
news:11********************@c13g2000cwb.googlegrou ps.com...
[Mystic] wrote:

I wanted to do something similar, like having a mysql class
that there can only be one of. The purpose of this was not
to have hundereds to mysql connections open,


Well, let's start by reading PHP documentation:

If a second call is made to mysql_connect() with the same
arguments, no new link will be established, but instead,
the link identifier of the already opened link will be
returned.

http://www.php.net/manual/en/function.mysql-connect.php

So there's no need to use singletons for this purpose. MySQL
is capable of doing it on its own.

Cheers,
NC


Thanks
Jul 17 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Tim Clacy | last post by:
Is there such a thing as a Singleton template that actually saves programming effort? Is it possible to actually use a template to make an arbitrary class a singleton without having to: a)...
10
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
1
by: Jim Strathmeyer | last post by:
So I'm trying to implement a singleton template class, but I'm getting a confusing 'undefined reference' when it tries to link. Here's the code and g++'s output. Any help? // singleton.h ...
3
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic...
7
by: Ethan | last post by:
Hi, I have a class defined as a "Singleton" (Design Pattern). The codes are attached below. My questions are: 1. Does it has mem leak? If no, when did the destructor called? If yes, how can I...
3
by: Harry | last post by:
Hi ppl I have a doubt on singleton class. I am writing a program below class singleton { private: singleton(){}; public: //way 1
5
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++...
6
by: Manuel | last post by:
Consider the classic singleton (from Thinking in C++): ----------------------------------------------------- //: C10:SingletonPattern.cpp #include <iostream> using namespace std; class...
3
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That...
3
by: stevewilliams2004 | last post by:
I am attempting to create a singleton, and was wondering if someone could give me a sanity check on the design - does it accomplish my constraints, and/or am I over complicating things. My design...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.