Singleton - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of Singleton.php

  1. <?php
  2.  
  3. class DbConnector {
  4.     private static $instances = [];
  5.     
  6.     protected function __construct() { }
  7.     
  8.     protected function __clone() { }
  9.     
  10.     public function __wakeup() {
  11.         throw new \Exception("Cannot unserialized singleton");
  12.     }
  13.     
  14.     public static function getInstance() {
  15.         $subclass = static::class;
  16.         if(!isset(self::$instances[$subclass])) {
  17.             self::$instances[$subclass] = new static;
  18.         }
  19.         return self::$instances[$subclass];
  20.     }
  21. }
File Description
  • Singleton
  • PHP Code
  • 06 Nov-2019
  • 506 Bytes
You can Share it: