Skip to content

Instantly share code, notes, and snippets.

@ircmaxell
Created February 23, 2012 14:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ircmaxell/1893073 to your computer and use it in GitHub Desktop.
Flyweight Enums
<?php
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 {}
MyEnum::initialize();
<?php
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