-2

Is this the right way if I want properly write a Singleton class so that a maximum of one SingleClass object exists.

<?php
class SingleClass
{
    static $object;

    static public function getSingleton()
    {
        if(!isset(self::$object))
        {
            self::$object = new SingleClass();
        }
        return self::$object;
    }

    private function __construct()
    {

    }

}
$mySingle1 = SingleClass::getSingleton();   // one object made
$mySingle2 = SingleClass::getSingleton();   // reference to first object returned
$mySingle3 = SingleClass::getSingleton();   // reference to first object returned
?>

if this is how it's done how can I do a check on it with if/else functions?

Sam
  • 7,252
  • 16
  • 46
  • 65
Dora
  • 6,776
  • 14
  • 51
  • 99
  • oops thanks I thought I gave them all that arrow up saying answer is useful and said thanks to them too... – Dora Jun 03 '13 at 00:42

1 Answers1

3

Yes this is a singleton in php. My only edit would be to restrict the clone operation. This can be done by throwing an exception within the __clone magic method

Orangepill
  • 24,500
  • 3
  • 42
  • 63
  • I just gave you a **[Silver](http://stackoverflow.com/badges/19/enlightened)** Badge. For passing my mark in three weeks – samayo Jun 03 '13 at 00:32