I found recommend not to use "extend" for such patterns.
<?php final class SingletonLib { /** * @var array<class-string, object> */ private static $singleton_array = []; /** * @param string $classname * * @return object * * @template TInit as object * @phpstan-param class-string<TInit> $classname * @phpstan-return TInit */ public static function init($classname) { if (!isset(self::$singleton_array[$classname])) { self::$singleton_array[$classname] = new $classname(); } /* @phpstan-ignore-next-line | static magic */ return self::$singleton_array[$classname]; } /** * @param string $classname * * @return object * * @template TInit as object * @phpstan-param class-string<TInit> $classname * @phpstan-return TInit|null */ public static function get($classname) { if (!isset(self::$singleton_array[$classname])) { return null; } /* @phpstan-ignore-next-line | static magic */ return self::$singleton_array[$classname]; } /** * @return array<class-string, object> */ public static function getAll() { return self::$singleton_array; } }
class Database { public function connect() { // ... } /** * @return static */ public static function singleton() { return SingletonLib::init(static::class); } }
PS: you maybe do not need this at all because you can move this decision into your container e.g.: container.thephpleague.com/4.x/def...
Thanx for detailed comment
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I found recommend not to use "extend" for such patterns.
PS: you maybe do not need this at all because you can move this decision into your container e.g.: container.thephpleague.com/4.x/def...
Thanx for detailed comment