<?php
class Singleton
{
private static $instances = [];
private function __construct()
{
// Private constructor so nobody else can instance it
}
public static function getInstance()
{
$subClass = static::class;
if (!isset(self::$instances[$subClass])) {
self::$instances[$subClass] = new static;
}
return self::$instances[$subClass];
}
protected function __clone()
{
throw new \Exception('Cannot clone');
}
protected function __wakeup()
{
throw new \Exception('Cannot unserialize');
}
}
class SingletonChildA extends Singleton
{
}
class SingletonChildB extends Singleton
{
}
$singletonA1 = SingletonChildA::getInstance();
$singletonA2 = SingletonChildA::getInstance();
$singletonB1 = SingletonChildB::getInstance();
$singletonB2 = SingletonChildB::getInstance();
var_dump($singletonA1 === $singletonA2); // true
var_dump($singletonB1 === $singletonB2); // true
var_dump($singletonA1 === $singletonB1); // false
var_dump($singletonA2 === $singletonB2); // false