Skip to content

Instantly share code, notes, and snippets.

@sankety
Last active January 6, 2020 11:27
Show Gist options
  • Save sankety/8fef9f3f45d14c7a42514e9709e75152 to your computer and use it in GitHub Desktop.
Save sankety/8fef9f3f45d14c7a42514e9709e75152 to your computer and use it in GitHub Desktop.
Demo for Singleton design pattern in PHP
<?php
final class ASingleTon{
private static $counter = 0;
private static $instance = null;
public static function getInstance(){
if(!empty(ASingleTon::$instance)){
return ASingleTon::$instance;
}
ASingleTon::$instance = new ASingleTon();
return ASingleTon::$instance;
}
private function __construct(){
ASingleTon::$counter ++;
echo ASingleTon::$counter;
}
public function someMethod(){
return 'here we go';
}
}
//$obj = new ASingleTon(); // this wont work as the constructor is private
$instance = ASingleTon::getInstance();
echo $instance->someMethod();
$instance1 = ASingleTon::getInstance();
echo $instance1->someMethod();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment