Last active
May 12, 2022 14:33
-
-
Save mikoj/e95cc1200c9c5c5bf3707e282314cde3 to your computer and use it in GitHub Desktop.
php7 Singleton final private __construct
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 | |
interface ISingleton { | |
public static function getInstance(): ISingleton; | |
} | |
abstract class Singleton implements ISingleton { | |
private static $_instances = []; | |
final private function __construct () {} | |
final private function __clone() {} | |
final private function __wakeup() {} | |
final public static function getInstance() : ISingleton { | |
self::$_instances[static::class] = self::$_instances[static::class] ?? new static(); | |
return self::$_instances[static::class]; | |
} | |
} | |
class Person extends Singleton { | |
public $age = 0; | |
} | |
class Man extends Person { | |
} | |
class Woman extends Person { | |
} | |
$person1 = Person::getInstance(); | |
$person1->age = 1; | |
$man1 = Man::getInstance(); | |
$man1->age = 2; | |
$woman1 = Woman::getInstance(); | |
$woman1->age = 3; | |
var_dump($person1, $man1, $woman1, Person::getInstance(), Man::getInstance(), Woman::getInstance()); |
@thefrosty thx
Some warnings will be here if you're using php 8.0 and above:
Warning: Private methods cannot be final as they are never overridden by other classes in /home/user/scripts/code.php on line 11
Warning: Private methods cannot be final as they are never overridden by other classes in /home/user/scripts/code.php on line 12
Warning: The magic method Singleton::__wakeup() must have public visibility in /home/user/scripts/code.php on line 12
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you're going the PHP 7 route, you can change
$className
tostatic::class
and removeget_called_class()
.