bonndan / phpenums
此包的最新版本(0.1.0)没有可用的许可信息。
PHP7的实验性枚举实现
0.1.0
2017-01-27 22:10 UTC
Requires
- php: ^7
Requires (Dev)
- phpunit/phpunit: 5.6.2
This package is not auto-updated.
Last update: 2024-09-23 16:20:23 UTC
README
PHP中枚举的另一种实现。与其他实现的不同之处在于,该实现非常接近Java。使用静态属性,但像在Java中一样,它们是枚举的真正实例,提供所有方法等。
class Fruit extends \Pava\Enum { /** * @var Fruit */ public static $APPLE; /** * @var Fruit */ public static $BANANA; }
因此可以使用静态类型
$mix = function (Fruit $a, Fruit $b) {}; $blend = $mix(Fruit::$APPLE, Fruit::$BANANA); $grow = function () : Fruit { return Fruit::$APPLE }; assert(Fruit::$APPLE instanceof Fruit);
缺点是什么?
- 每个枚举都必须注册(除非PHP中到来静态构造函数)。原因是静态属性只能具有标量值作为默认值。
//class Fruit ... Pava\register(Fruit::class);
- 需要注释所有静态属性以便IDE能够正常工作,但至少这可行。
- 不可用默认值。在“编译时”$BANANA 还不是实例。然而,可以使用null作为默认值。
//not possible $a = function (Fruit $a = Fruit::$BANANA) {};
- 无法使用/导入,即不能直接写$BANANA。
高级使用
每个枚举实例可以通过实现魔术调用方法来获取自己的属性。
class Fruit extends \Pava\Enum { private $color; /** * @var Fruit */ public static $APPLE; /** * @var Fruit */ public static $BANANA; public function color() : string { return $this->color; } public function __invoke() { if ($this->name() == 'BANANA') $this->color = 'yellow'; if ($this->name() == 'APPLE') $this->color = 'green'; } } Pava\register(Fruit::class); echo 'The apple is ' . Fruit::$APPLE->color();