-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-singleton.php
More file actions
executable file
·86 lines (70 loc) · 1.62 KB
/
class-singleton.php
File metadata and controls
executable file
·86 lines (70 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/**
* Class Singleton
*
* @package wpct-plugin
*/
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
namespace WPCT_PLUGIN;
use Error;
if ( ! defined( 'ABSPATH' ) ) {
exit();
}
/**
* Singleton abstract class.
*/
abstract class Singleton {
/**
* Handle singleton instances map.
*
* @var object[]
*/
private static $instances = array();
/**
* Controlled class contructor.
*
* @param boolean &$singleton Pointer to a boolean handler to be set as true by the constructor.
*/
public function __construct( &$singleton ) {
$singleton = true;
}
/**
* Prevent class clonning.
*/
final public function __clone() {
}
/**
* Prevent class serialization.
*
* @throws Error Each time the method is called.
*/
final public function __wakeup() {
throw new Error( 'Cannot unserialize a singleton.' );
}
/**
* Abstract singleton class constructor.
*
* @param mixed[] ...$args Class constructor arguments.
*/
abstract protected function construct( ...$args );
/**
* Get class instance.
*
* @return object $instance class instance
*
* @throws Error If no instance is found.
*/
final public static function get_instance() {
$args = func_get_args();
$cls = static::class;
if ( ! isset( self::$instances[ $cls ] ) ) {
// Pass $singleton reference to prevent singleton classes constructor overwrites.
self::$instances[ $cls ] = new static( $singleton );
if ( ! $singleton ) {
throw new Error( 'Cannot create uncontrolled instances from a singleton.' );
}
self::$instances[ $cls ]->construct( ...$args );
}
return self::$instances[ $cls ];
}
}