Hello
From my understanding, PHP does not offer a `built-in' enum type. People usually recommend using an array to model an enum, since they are a map(key, value). Maybe I am misinterpreting this advice, but I have built a class where the set methods check that the parameter is a value in such a map, before changing the underlying, private property. Example:
While this works, the problem is that external classes cannot access the arrays directly. Either i'd have to make them public, which defeats the purpose since they should not be modified, or I'd have to add another get function for each of the arrays. What I would like to do, is make them public, but constant, i.e. read-only. From reading the php documentation, the language does not support this. As an alternative, I am considering to create a class for each of these enumerated properties, but I `feel' that would be excessive. I would love to hear your take on this issue.
From my understanding, PHP does not offer a `built-in' enum type. People usually recommend using an array to model an enum, since they are a map(key, value). Maybe I am misinterpreting this advice, but I have built a class where the set methods check that the parameter is a value in such a map, before changing the underlying, private property. Example:
Code:
[color=lightblue]class[/color] LoanData{
[color=lightblue]private[/color] $UndertakingType;
[color=lightblue]private static[/color] $EnumUndertaking = [color=lightblue]array[/color]('Kauf', 'Bau', 'Renovierung',
'Anschlussfinanzierung',
'Kapitalbeschaffung');
[color=lightblue]function[/color] setUndertakingType($type){
[color=lightblue]self[/color]::checkEnum($this->UndertakingType, [color=lightblue]self[/color]::$EnumUndertaking, $type);
}
[color=lightblue]private static function[/color] checkEnum(&$val, &$list, $type){
if(!in_array($type, $list)){
die('Typed Valued out of bounds');
}
$val = $type;
}
}
While this works, the problem is that external classes cannot access the arrays directly. Either i'd have to make them public, which defeats the purpose since they should not be modified, or I'd have to add another get function for each of the arrays. What I would like to do, is make them public, but constant, i.e. read-only. From reading the php documentation, the language does not support this. As an alternative, I am considering to create a class for each of these enumerated properties, but I `feel' that would be excessive. I would love to hear your take on this issue.