Created
December 14, 2018 16:37
-
-
Save gotraveltoworld/e070cef447bc73808ccf8c4adf3509f1 to your computer and use it in GitHub Desktop.
Use the PHP to implement the Singleton Pattern.
This file contains 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 | |
/** | |
* Design Pattern of the Singleton. | |
*/ | |
class Singleton | |
{ | |
private static $instance = null; | |
/** | |
* Call this method to get singleton | |
* | |
* @return Singleton | |
*/ | |
public static function getSingleton() | |
{ | |
if (self::$instance === null) { | |
self::$instance = new self(); | |
} | |
return self::$instance; | |
} | |
/** | |
* Call this method to get singleton | |
* | |
* @return string | |
*/ | |
public function responseString() | |
{ | |
return 'Well done.'; | |
} | |
} | |
// Cal the inside member. | |
echo (Singleton::getSingleton())->responseString(). "\n"; | |
// Testing... | |
class A extends Singleton {} | |
class B extends Singleton {} | |
echo get_class(A::getSingleton()). "\n"; | |
echo get_class(B::getSingleton()). "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment