PHP 5.3 and typesafe enumerations

at 2008-08-12 in PHP5 by friebe (0 comments)

Within RFC #0132, typesafe enumerations were added to the XP framework. Because PHP does not support them language-wise, we need a bit of workaround syntax to make them work.

With PHP 5.3 and its so-called "late static binding features", enum declarations can now be written much more compact for the simplest use-case. Example:

  class TransactionType extends Enum {
public
static $NOT_SUPPORTED, $REQUIRED, $SUPPORTS, $NEVER;
}

Previously, we needed to write this as follows:

  class TransactionType extends Enum {
public
static $NOT_SUPPORTED, $REQUIRED, $SUPPORTS, $NEVER;

static function __static() {
self::
$NOT_SUPPORTED= new self(0, 'NOT_SUPPORTED');
self::
$REQUIRED= new self(1, 'REQUIRED');
self::
$SUPPORTS= new self(2, 'SUPPORTS');
self::
$NEVER= new self(3, 'NEVER');
}

public
static function values() {
return parent::membersOf
(__CLASS__);
}
}


See also the 5.3 experiments: lsb/enum.



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases
5.8-SERIES
Unicode
Language
5.9-SERIES

Related

Find related articles by a search for «PHP».