Skip to content

Instantly share code, notes, and snippets.

@tnylea
Last active March 2, 2018 18:39
Show Gist options
  • Save tnylea/6dc5d447015e38bcbbc4238a9319c570 to your computer and use it in GitHub Desktop.
Save tnylea/6dc5d447015e38bcbbc4238a9319c570 to your computer and use it in GitHub Desktop.
Example PHP singleton class
<?php
class Greeting
{
// Hold an instance of the class
private static $instance;
private static $name;
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
self::$instance = new Greeting;
}
return self::$instance;
}
public static function setName($name){
self::$name = $name;
}
public static function getName(){
return self::$name;
}
}
$greeting = Greeting::singleton();
$greeting->setName('Tony');
echo $greeting->getName();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment