Created
December 21, 2021 14:44
-
-
Save DaveDevYT/b9046b404c5ce5546ba12b6d9bd66d5e to your computer and use it in GitHub Desktop.
Singleton exercise
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 | |
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