1 <?php
2
3 /**
4 * Trait for singletons.
5 *
6 * @author gharlan
7 *
8 * @package redaxo\core
9 */
10 trait rex_singleton_trait
11 {
12 /**
13 * Singleton instances.
14 *
15 * @var static[]
16 */
17 private static $instances = [];
18
19 /**
20 * Returns the singleton instance.
21 *
22 * @return static
23 */
24 public static function getInstance()
25 {
26 $class = static::class;
27 if (!isset(self::$instances[$class])) {
28 self::$instances[$class] = new static();
29 }
30 return self::$instances[$class];
31 }
32
33 /**
34 * Cloning a singleton is not allowed.
35 *
36 * @throws BadMethodCallException
37 */
38 final public function __clone()
39 {
40 throw new BadMethodCallException('Cloning "' . get_class($this) . '" is not allowed!');
41 }
42 }
43