Skip to content

Instantly share code, notes, and snippets.

@kilip
Last active November 16, 2015 14:41
Show Gist options
  • Save kilip/e32a40e8f49be7cd27e0 to your computer and use it in GitHub Desktop.
Save kilip/e32a40e8f49be7cd27e0 to your computer and use it in GitHub Desktop.
Singleton Design Pattern
<?php
class Counter
{
protected $count = 0;
static private $instance = null;
// protected will ensure that this class only created once
protected function __construct()
{
}
/**
* Private __clone will prevent cloning of the instance of the "Singleton" object
*/
protected function __clone()
{
}
/**
* Private __wakeup method to prevent unserializing of the *Singleton*
* instance.
*/
private function __wakeup()
{
}
public function getCount()
{
return $this->count;
}
public function setCount($count)
{
$this->count = $count;
}
// create an object if not already created
// returns the current instance of object
static public function getInstance()
{
if(null === static::$instance){
static::$instance = new static();
}
return static::$instance;
}
}
$ob1 = Counter::getInstance();
$ob1->setCounter(5);
echo Counter::getInstance()->getCount();// will output 5;
Counter::getInstance()->setCount(4);
$ob2 = Counter::getInstance();
echo $ob2->getCount();//will output 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment