开发者

what is the exact difference between PHP static class and singleton class

开发者 https://www.devze.com 2022-12-30 08:04 出处:网络
I have always used a Singleton class for a registry object in PHP. As all Singleton classes I think the main method looks like this:

I have always used a Singleton class for a registry object in PHP. As all Singleton classes I think the main method looks like this:

class registry
{
    public static function singleton()
    {
        if( !isset( self::$instance ) )
        {
            self::$instance = new registry();
        }
        return self::$instance;
    }

    public function doSomething()
    {
        echo 'something';
    }
}

So whenever I need something of the registry class I use a function like this:

registry::singleton()->doSomethine();

Now I do not understand what the difference is between creating just a normal static function. Will it create a new object if I just use a 开发者_JAVA技巧normal static class.

class registry
{
    public static function doSomething()
    {
        echo 'something';
    }
}

Now I can just use:

registry::doSomethine();

Can someone explain to me what the function is of the singleton class. I really do not understand this.


A static function is a function that can be called without creating an object of a class.

registry::doSomething()

A Singleton is a design pattern, that should prevent the users of the class from creating more than one instance of a class. So, there is usually only one instance of a singleton class. A Singleton's constructor should be declared private and have a static method providing a single instance-object:

class Singleton
{
   private Singleton()
   {
   }

   private static var $instance = null;

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

For more information see http://en.wikipedia.org/wiki/Singleton_pattern

P.S: Sorry for my bad PHP, the syntax may not be 100% correct, but you should roughly understand what I mean in terms of OOP.


The fact that the Singleton is a design-pattern that restricts instantiation of a class to one single object, it is possible to do some stuff that is slightly more difficult with a static class:

  • Lazy initialization
  • Replace implementation internally by sub-classing the Factory
  • Manage via configuration

However, there are several drawbacks to singletons, so it is better in general to use patterns such as Factory as you get additional benefits such as decoupling.

0

精彩评论

暂无评论...
验证码 换一张
取 消