Last active
August 29, 2015 14:06
-
-
Save serjoscha87/7b506d76d87c316eaf6a to your computer and use it in GitHub Desktop.
This simple Singleton PHP-Class enables an easy *encapsulating of class attributes and methods* with the benefit of standard Singleton "features" (no need of an instance). The only clue: encapsulating! That enables to hide attributes and even methods for the user of your class (which extends the simple Singleton class). On this way you are able …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Singleton { | |
| protected static $inst = null; | |
| protected static function getInstance($c2i) { | |
| if(self::$inst === null) | |
| self::$inst = new $c2i; | |
| return self::$inst; | |
| } | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * This demonstrates the the Singleton Class purpose | |
| */ | |
| class AnySingletonClass extends Singleton { | |
| private $foo = "bar"; // this is private an can not be accessed via AnySingletonClass::$bar but via the getter and setter AnySingletonClass::setFoo(<nuVal>) | |
| /** | |
| * @return AnySingletonClass | |
| */ | |
| private static function i() { | |
| return self::getInstance(AnySingletonClass); | |
| } | |
| public static function setFoo($val) { | |
| self::i()->foo = $val; | |
| } | |
| public static function getFoo() { | |
| return self::i()->foo; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment