PHP5 Singleton Design Pattern


/ Published in: PHP
Save to your folder(s)

A Singleton design pattern in PHP.


Copy this code and paste it in your HTML
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. /**
  5.  * Singleton design pattern implementation
  6.  */
  7. class Singleton {
  8.  
  9. /** @var object[] */
  10. private static $instances = [];
  11.  
  12. private function __construct() {
  13. }
  14.  
  15. /**
  16.   * @param string $class The class name to invoke
  17.   *
  18.   * @return mixed
  19.   */
  20. public static function getInstance(string $class) {
  21. if (!array_key_exists($class, self::$instances)) {
  22. self::$instances[$class] = new $class();
  23. }
  24. return self::$instances[$class];
  25. }
  26. }
  27.  
  28. // Usage - provide a class name to getInstance to invoke it
  29. $instance = Singleton::getInstance(Singleton::class);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.