andybeak
1/12/2017 - 11:02 AM

Singleton trait

Singleton trait

<?php
trait Singleton
{
  private static $instance;

  private function __construct() {}

  public static function getInstance()
  {
      if (!(self::$instance instanceof self)) {
          self::$instance = new self;
      }
      return self::$instance;
  }

}

class MyClass
{
  use Singleton;
}

$object = MyClass::getInstance();   // object of type MyClass

$object = new MyClass;  // PHP fatal error