Skip to content

Instantly share code, notes, and snippets.

@serjoscha87
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save serjoscha87/7b506d76d87c316eaf6a to your computer and use it in GitHub Desktop.

Select an option

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 …
class Singleton {
protected static $inst = null;
protected static function getInstance($c2i) {
if(self::$inst === null)
self::$inst = new $c2i;
return self::$inst;
}
}
/**
* 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