Page 1 of 1

Singleton vs Abstract + Static

Posted: Tue Jul 26, 2005 10:34 pm
by stukov
What is the main difference between a singleton and an abstract class with only static methods and functions? I mean, both of these will only get one "instance".

Is there any performance difference?

Posted: Wed Jul 27, 2005 7:42 am
by timvw
There is significant difference.

Possible instances of an abstract class: 0
Possible instances of a singleton class: 1


An abstract class is abstract, and can't be instantiated per definition.

Posted: Wed Jul 27, 2005 10:13 am
by stukov
Yes, I know that theorically, you can't have an instance of the abstract class, but while using it with static methods and functions, it appears to be "like" an "instance" of the class itself. May these line of code explain. Let's consider:

Code: Select all

class one {
var $foo;

  function bar() {
    $this->foo = 4;
  }
}
and

Code: Select all

abstract class Singleton {
  static $foo;
    
  function bar() {
    self::$foo = 4;
  }
}
In both cases you will be able to print out the var $foo and you will get "4". Is one of these ways to design a "singleton" is better than an other (let's say in an extreme environnement - 100 000 visits / minute).

Posted: Wed Jul 27, 2005 2:30 pm
by timvw
Is one of these ways to design a "singleton" is better than an other.
Well, if you are going to implement a singleton, it would make sense to have code that allows you to have a single instance...

Here are some alternatives to implement a singleton: http://www.tonymarston.net/php-mysql/singleton.html.

You are allowed to do some benchmarks on the implementations and let us know what the outcome was :)

Posted: Wed Jul 27, 2005 8:47 pm
by stukov
timvw: thanks for the link, it was very helpful.
timvw wrote:You are allowed to do some benchmarks on the implementations and let us know what the outcome was :)
All right, I'll try this tonight. I'll be back in a while with the results :D.

Posted: Thu Jul 28, 2005 3:59 am
by McGruff
Oh God the dreaded Tony Marston... Steer well clear unless you want to be set back several years in your understanding of OOP.

Some better reading material: http://www.phppatterns.com/index.php/ar ... ew/75/1/1/.

Posted: Thu Jul 28, 2005 11:10 am
by Ambush Commander
Why don't you just (and this is PHP4) stick the singleton in a global variable and take care not to call it again?