Skip to content

Instantly share code, notes, and snippets.

@maximgrynykha
Last active January 20, 2022 11:51
Show Gist options
  • Save maximgrynykha/3becc4e8dc0e0a37298630168962b622 to your computer and use it in GitHub Desktop.
Save maximgrynykha/3becc4e8dc0e0a37298630168962b622 to your computer and use it in GitHub Desktop.
Singleton Pattern [PHP 8.1+]
<?php
trait Singleton
{
/**
* @var static[]
*/
protected static $instances = [];
/**
* @see https://refactoring.guru/design-patterns/singleton/php/example
*
* @return static
*/
public static function instance(): static
{
return static::$instances[static::class] ??= new static();
}
/**
* @see https://www.php.net/manual/en/language.oop5.decon.php#object.construct
*
* @return void
*/
protected function __construct(){}
/**
* @see https://www.php.net/manual/en/language.oop5.cloning.php#object.clone
*
* @return void
*/
protected function __clone(){}
/**
* @see https://www.php.net/manual/en/language.oop5.magic.php#object.sleep
*
* @return void
*/
protected function __sleep(){}
/**
* @see https://www.php.net/manual/en/language.oop5.magic.php#object.wakeup
*
* @return void
*/
protected function __wakeup(){}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment