note 69528 deleted from language.oop5 by felipe
| From: | felipe@php.net | Date: | Mon, 24 Mar 2008 22:10:58 +0000 |
| Subject: | note 69528 deleted from language.oop5 by felipe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137469@lists.php.net to get a copy of this message | ||
Note Submitter: devoid at digital-ritual dot net
----
After several hours of trying different patterns I have finally figured out a decent method of
emulating the concept of TypeSafe ENUM (Java/C++/etc.) with PHP5. Below is an example from a logging
application that I am working on.
<code>
/**
* First we need to define a class to act as our 'type'
*/
final class LogLevel extends Object {
private $lvl;
private $description;
public function __construct($lvl,$desc) {
$this->lvl = $lvl;
$this->description = $desc;
}
public function getDescription() {
return $this->description;
}
public function getLevel() {
return $this->lvl;
}
public static function createLevel($lvl,$desc) {
return new LogLevel($lvl,$desc);
}
public static function getByLevel($lvl) {
if (gettype($lvl) !== 'int') {
throw new InvalidArgumentException();
}
foreach (self::$logLevels as $logLevel) {
$level = $logLevel;
if ($lvl < $logLevel->getLevel()) {
break;
}
}
return $level;
}
}
/**
* Here is the part where I ran into problems. I need to make
* 'constant-values' for the static 'Enum Array' as you can
* not set a static object-scope variable to the results of
* a function at classload time as you can in Java. Several
* people might consider this 'bad-form' in PHP spec, however
* it is the only way I have found to accomplish this feat.
*/
define('LVL_BASIC', new LogLevel(1, 'BASIC'));
define('LVL_ERROR', new LogLevel(5, 'ERROR'));
define('LVL_WARN', new LogLevel(10, 'WARN'));
define('LVL_BASIC', new LogLevel(20, 'INFO'));
define('LVL_DEBUG', new LogLevel(50, 'DEBUG'));
</code>
Now we need to add our static 'enum' to the class which acts as our type. This
'Enum' will allow us to get an Enum value by id, description, or any other internal
property which is part of your class.
<code>
/**
* Add this line to the LogLevel Class
*/
private static $logLevels = array(LVL_BASIC, LVL_ERROR, LVL_WARN, LVL_INFO, LVL_DEBUG);
</code>
I am sure there is probably a way that I could have accomplished something similar by extending
PHP's Array classes however, this seemed a much easier and more abstract approach to the
problem.