tmilos/value

抽象值和枚举对象

2.0.1 2016-12-26 13:52 UTC

This package is not auto-updated.

Last update: 2024-09-10 20:40:30 UTC


README

抽象值和枚举对象

License Build Status Coverage Status Scrutinizer Code Quality SensioLabsInsight

值对象

class IntValue extends AbstractValue
{
    public static function isValid($value)
    {
        return is_int($value);
    }
}

$x = new IntValue(10); // ok
print $x->getValue(); // 10
$y = new IntValue(10);
var_dump($x->equal($y)); // true

$z = new IntValue('20'); // throws \UnexpectedValueException

枚举值对象

所有类定义的常量都是有效值,可以使用与该常量相同的名字的魔法方法来实例化具有该值的枚举。

class Gender extends AbstractEnum
{
    const MALE = 'male';
    const FEMALE = 'female';

    private static $titles = [
        self::MALE => 'gender.male',
        self::FEMALE => 'gender.female',
    ];

    public function getTitle()
    {
        return self::$titles[$this->getValue()];
    }
}

var_dump(Gender::all());    // ['male' => Gender() => 'female' => Gender() ]
var_dump(Gender::values()); // [ 0 => 'male', 1 => 'female' ]
$m = Gender::MALE();
print $m->getValue(); // male
print $m->getTitle(); // gender.male
var_dump(Gender::isValid('male')); // true
var_dump(Gender::isValid('something')); // false