Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Flyweight Enums
abstract class MyEnum {
private static $initialized = false;
private static $values = array();
public static function initialize() {
self::$values['MyFirstValue'] = new MyFirstValue(1);
self::$values['MySecondValue'] = new MySecondValue(2);
self::$values['MyThirdValue'] = new MyThirdValue(3);
public static function __callStatic($name, array $arguments) {
if (isset(self::$values[$name])) {
return self::$values[$name];
} else {
return null;
private $value = 0;
private function __construct($value) {
$this->value = $value;
public function __toString() {
return get_class($this);
public function value() {
return $this->value;
final class MyFirstValue extends MyEnum {}
final class MySecondValue extends MyEnum {}
final class MyThirdValue extends MyEnum {}
require 'flyweight.php';
$first = MyEnum::MyFirstValue();
var_dump($first instanceof MyEnum); // true
var_dump($first->value()); // 1
var_dump((string) $first); // 'MyFirstValue'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.