Last active
January 6, 2020 11:27
-
-
Save sankety/8fef9f3f45d14c7a42514e9709e75152 to your computer and use it in GitHub Desktop.
Demo for Singleton design pattern in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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