garoevans/php-enum

提供一种方便的方式,始终可以使用Enum对象,并在可用的情况下使用Spl Types。

1.2.0 2014-10-09 22:41 UTC

README

这为我们提供了一个方便的方式来始终可以使用Enum对象,并在可用的情况下使用Spl Types。它可能会在有些IDE中引起一些麻烦,因为它会看到两个同名类,但我们知道这不是问题,因为代码是好的 :)

我们还包装了SplEnum类,以阻止IDE认为构造函数参数是必要的。强制其按照文档所述的方式行动。

替代品与Spl Enum的预期使用紧密相连,您可以直接使用https://php.ac.cn/manual/en/class.splenum.php文档;

use Garoevans\PhpEnum\Enum;

class Fruit extends Enum
{
    // If no value is given during object construction this value is used
    const __default = self::APPLE;
    // Our enum values
    const APPLE     = 1;
    const ORANGE    = 2;
}

$myApple  = new Fruit();
$myOrange = new Fruit(Fruit::ORANGE);
$fail     = 1;

function eat(Fruit $aFruit)
{
    if ($aFruit->is(Fruit::APPLE)) {
        echo "Eating an apple.\n";
    } else if ($aFruit->is(Fruit::ORANGE)) {
        echo "Eating an orange.\n";
    }
}

// Eating an apple.
eat($myApple);
// Eating an orange.
eat($myOrange);

// PHP Catchable fatal error:  Argument 1 passed to eat() must be an
// instance of Fruit, integer given
eat($fail);

除了标准化Spl Enum构造函数之外,还包括了以下功能:通过与期望的常量同名的静态方法以简短的方式实例化。使用上面提到的Fruit类,我们可以这样做;

// Eating an apple.
eat(Fruit::APPLE());

此外,还提供了constantExists()方法供使用;

$fruit = new Fruit();
if ($fruit->constantExists("apple")) {
    echo "Apple is available.\n";
}