dkd/enumeration

PHP 的枚举实现。

0.1 2014-08-28 06:00 UTC

This package is not auto-updated.

Last update: 2024-09-10 02:14:48 UTC


README

这是一个为PHP >= 5.3添加枚举支持的本地PHP实现。它是一个抽象类,需要扩展后才能使用。

用法

基础

use Dkd\Enumeration;

class MyEnumeration extends Enumeration
{
    // this is optional. The value will be used as default value if no value
    // is given.
    const __DEFAULT = self::INTEGER_VALUE;

    // all scalar datatypes are supported
    const INTEGER_VALUE = 1;
    const FLOAT_VALUE = 0.123;
    const STRING_VALUE = 'foo';
    const BOOLEAN_VALUE = true;
}

// Use the ```__DEFAULT``` value if defined. If not defined an exception
// is thrown.
$myEnumeration = MyEnumeration();

$myEnumeration = new MyEnumeration(MyEnumeration::INTEGER_VALUE);

// cast does automatically cast the given value to the enumeration value.
$myEnumeration = MyEnumeration::cast(MyEnumeration::INTEGER_VALUE);
$myEnumeration = MyEnumeration::cast($myEnumeration);
$myEnumeration = MyEnumeration::cast($databaseResult['my_column']);

// get all possible values of the enumeration.
$possibleValues = MyEnumeration::getConstants();

$myEnumeration = new MyEnumeration(MyEnumeration::INTEGER_VALUE);
$myEnumeration->equals(1); // TRUE
$myEnumeration->equals($myEnumeration); // TRUE
$myEnumeration->equals(0.123); // FALSE
$myEnumeration->equals('foo'); // FALSE
$myEnumeration->equals(new MyEnumeration('foo')); // FALSE

为什么不使用 SplEnum

  • SplEnum 并非PHP内建,需要安装pecl扩展。

安装

Composer

dkd/enumeration 添加到项目的 composer.json 依赖中,并运行 php composer.phar install

GIT

git clone git://github.com/dkd/enumeration.git

ZIP / TAR

Github下载最新版本并解压。

许可证

此代码也是TYPO3 CMS项目的一部分,并已提取到此包中。请参阅LICENSE以获取详细信息。