Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created February 8, 2021 16:09
Show Gist options
  • Select an option

  • Save kobus1998/03de94e9205562f695113202ad160fff to your computer and use it in GitHub Desktop.

Select an option

Save kobus1998/03de94e9205562f695113202ad160fff to your computer and use it in GitHub Desktop.
extendable singleton class
<?php
class Singleton
{
protected static $instanches = [];
private function __construct()
{
}
public static function instance()
{
if (!isset(self::$instances[static::class])) {
self::$instanches[static::class] = new static();
}
return self::$instanches[static::class];
}
}
class Foo extends Singleton
{
private $a = 'a';
public function get()
{
echo $this->a;
}
}
class Bar extends Singleton
{
private $b = 'b';
public function get()
{
echo $this->b;
}
}
echo Foo::instance()->get(); // a
echo Bar::instance()->get(); // b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment