Skip to content

Instantly share code, notes, and snippets.

@DaveDevYT
Created December 21, 2021 14:44
Show Gist options
  • Save DaveDevYT/b9046b404c5ce5546ba12b6d9bd66d5e to your computer and use it in GitHub Desktop.
Save DaveDevYT/b9046b404c5ce5546ba12b6d9bd66d5e to your computer and use it in GitHub Desktop.
Singleton exercise
<?php
class SingletonClass
{
private static ?SingletonClass $instance = null;
private int $counter;
private function __construct()
{
$this->counter = 0;
}
public static function GetInstance() : SingletonClass
{
if(!self::$instance)
{
self::$instance = new SingletonClass();
}
return self::$instance;
}
public function PrintAndIncrease()
{
$this->counter++;
echo "Counter: ".$this->counter."<br/>";
}
}
$instance = SingletonClass::GetInstance();
$instance->PrintAndIncrease();
$instance2 = SingletonClass::GetInstance();
$instance2->PrintAndIncrease();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment