Last active
March 8, 2024 07:25
-
-
Save amacgregor/8660951 to your computer and use it in GitHub Desktop.
PHP Singleton pattern example
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 | |
/** Example taken from http://www.webgeekly.com/tutorials/php/how-to-create-a-singleton-class-in-php/ **/ | |
class User | |
{ | |
// Hold an instance of the class | |
private static $instance; | |
// The singleton method | |
public static function singleton() | |
{ | |
if (!isset(self::$instance)) { | |
self::$instance = new __CLASS__; | |
} | |
return self::$instance; | |
} | |
} | |
$user1 = User::singleton(); | |
$user2 = User::singleton(); | |
$user3 = User::singleton(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this trait
then
Singleton
has only one responsibility: to be singleUser
has only one responsibility: to represent user