Skip to content

Instantly share code, notes, and snippets.

@adriacidre
Created May 2, 2013 19:21
Show Gist options
  • Save adriacidre/5504667 to your computer and use it in GitHub Desktop.
Save adriacidre/5504667 to your computer and use it in GitHub Desktop.
PHP Singleton pattern using traits
<?php
trait Singleton
{
private static $_instance;
private function __construct(){}
public function __clone()
{
throw new Exception('This object cannot be cloned!');
}
public static function getInstance()
{
if (null === static::$_instance) {
static::$_instance = new static();
}
return static::$_instance;
}
}
class Product
{
use Singleton;
}
$product = Product::getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment