Skip to content

Instantly share code, notes, and snippets.

@Xelom
Created February 22, 2017 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xelom/f32fbd1273b6d2f344e6457160feabba to your computer and use it in GitHub Desktop.
Save Xelom/f32fbd1273b6d2f344e6457160feabba to your computer and use it in GitHub Desktop.
Singleton

To create a singleton, make the constructor private, disable cloning, disable extension and create a static variable to house the instance

final class President {
    private static $instance;

    private function __construct() {
        // Hide the constructor
    }
    
    public static function getInstance() : President {
        if (!self::$instance) {
            self::$instance = new self();
        }
        
        return self::$instance;
    }
    
    private function __clone() {
        // Disable cloning
    }
    
    private function __wakeup() {
        // Disable unserialize
    }
}

Then in order to use

$president1 = President::getInstance();
$president2 = President::getInstance();

var_dump($president1 === $president2); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment