PHP Classes

SingletonTrait: Trait to implement the singleton design pattern

Recommend this page to a friend!
  Info   View files Example   View files View files (3)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 106 All time: 9,686 This week: 560Up
Version License PHP version Categories
singletontrait 1.0BSD License5.4PHP 5, Design Patterns, Traits


This package provides a trait to implement the singleton design pattern.

The trait provides functions that return a new instance of the class if none was created so far, or an already created instance of the class otherwise.

It may also force creating a new instance of the class even if another was created.

The trait uses reflection to call the class constructor passing any arguments as a list or as an array.

Picture of Aleksandar Zivanovic
  Performance   Level  
Name: Aleksandar Zivanovic <contact>
Classes: 16 packages by
Country: Serbia Serbia
Age: 30
All time rank: 16206 in Serbia Serbia
Week rank: 298 Up3 in Serbia Serbia Up
Innovation award
Innovation award
Nominee: 4x



require_once __DIR__ . '/trait.Singleton.php';
__DIR__ . '/class.Example.php';

$cat = Example::getSharedInstance('Cat', 'MEOW');
$brownCat = Example::getSharedInstance('Brown Cat', 'BREOW'); // Brown cat will sound same as $cat as its same instance
$dog = Example::getNewInstance('Dog', 'WOF');

$breakLine = php_sapi_name() === 'cli' ? "\n" : '<br>';


  Files folder image Files  
File Role Description
Plain text file class.Example.php Class Example class
Accessible without login Plain text file example.php Example Example script
Plain text file trait.Singleton.php Class Singleton Trait

 Version Control Unique User Downloads Download Rankings  
This week:0
All time:9,686
This week:560Up