note 87942 added to language.oop5
| From: | redrik at gmail dot com | Date: | Wed, 31 Dec 2008 21:08:53 +0000 |
| Subject: | note 87942 added to language.oop5 | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-148733@lists.php.net to get a copy of this message | ||
Maybe someone will find these classes, which simulate enumeration, useful.
<?php
class Enum {
protected $self = array();
public function __construct( /*...*/ ) {
$args = func_get_args();
for( $i=0, $n=count($args); $i<$n; $i++ )
$this->add($args[$i]);
}
public function __get( /*string*/ $name = null ) {
return $this->self[$name];
}
public function add( /*string*/ $name = null, /*int*/ $enum = null ) {
if( isset($enum) )
$this->self[$name] = $enum;
else
$this->self[$name] = end($this->self) + 1;
}
}
class DefinedEnum extends Enum {
public function __construct( /*array*/ $itms ) {
foreach( $itms as $name => $enum )
$this->add($name, $enum);
}
}
class FlagsEnum extends Enum {
public function __construct( /*...*/ ) {
$args = func_get_args();
for( $i=0, $n=count($args), $f=0x1; $i<$n; $i++, $f *= 0x2 )
$this->add($args[$i], $f);
}
}
?>
Example usage:
<?php
$eFruits = new Enum("APPLE", "ORANGE", "PEACH");
echo $eFruits->APPLE . ",";
echo $eFruits->ORANGE . ",";
echo $eFruits->PEACH . "\n";
$eBeers = new DefinedEnum("GUINESS" => 25, "MIRROR_POND" => 49);
echo $eBeers->GUINESS . ",";
echo $eBeers->MIRROR_POND . "\n";
$eFlags = new FlagsEnum("HAS_ADMIN", "HAS_SUPER", "HAS_POWER",
"HAS_GUEST");
echo $eFlags->HAS_ADMIN . ",";
echo $eFlags->HAS_SUPER . ",";
echo $eFlags->HAS_POWER . ",";
echo $eFlags->HAS_GUEST . "\n";
?>
Will output:
1, 2, 3
25, 49
1,2,4,8 (or 1, 10, 100, 1000 in binary)
----
Server IP: 208.69.120.35
Probable Submitter: 12.24.28.11
----
Manual Page -- http://www.php.net/manual/en/language.oop5.php
Edit -- https://master.php.net/note/edit/87942
Del: integrated -- https://master.php.net/note/delete/87942/integrated
Del: useless -- https://master.php.net/note/delete/87942/useless
Del: bad code -- https://master.php.net/note/delete/87942/bad+code
Del: spam -- https://master.php.net/note/delete/87942/spam
Del: non-english -- https://master.php.net/note/delete/87942/non-english
Del: in docs -- https://master.php.net/note/delete/87942/in+docs
Del: other reasons-- https://master.php.net/note/delete/87942
Reject -- https://master.php.net/note/reject/87942
Search -- https://master.php.net/manage/user-notes.php