Skip to content

Instantly share code, notes, and snippets.

@gotraveltoworld
Created December 14, 2018 16:37
Show Gist options
  • Save gotraveltoworld/e070cef447bc73808ccf8c4adf3509f1 to your computer and use it in GitHub Desktop.
Save gotraveltoworld/e070cef447bc73808ccf8c4adf3509f1 to your computer and use it in GitHub Desktop.
Use the PHP to implement the Singleton Pattern.
<?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