和对象的差异
尽管 enum 基于类和对象,但它们不完全支持对象相关的所有功能。 尤其是枚举条目不能有状态。
- 禁止构造、析构函数。
- 不支持继承。无法 extend 一个 enum。
- 不支持静态属性和对象属性。
- 由于枚举条目是单例对象,所以不支持对象复制
- 除了下面列举项,不能使用魔术方法。
以下对象功能可用,功能和其他对象一致:
- Public、private、protected 方法。
- Public、private、protected 静态方法。
- Public、private、protected 类常量。
- enum 可以 implement 任意数量的 interface。
-
枚举和它的条目都可以附加 注解。
目标过滤器
TARGET_CLASS
包括枚举自身。 目标过滤器TARGET_CLASS_CONST
包括枚举条目。 - 魔术方法:__call、__callStatic、 __invoke。
- 常量
__CLASS__
和__FUNCTION__
的功能和平时无差别
枚举类型的魔术常量 ::class
和对象完全一样,
它是个包含命名空间的类型名称。
由于枚举条目是枚举类型的一个实例,因此它的 ::class
也和枚举类型一样。
此外,不能用 new
直接实例化枚举条目,
也不能用 ReflectionClass::newInstanceWithoutConstructor() 反射实例化。
这么做都会导致错误。
<?php
$clovers = new Suit();
// Error: Cannot instantiate enum Suit
$horseshoes = (new ReflectionClass(Suit::class))->newInstanceWithoutConstructor()
// Error: Cannot instantiate enum Suit
?>

User Contributed Notes
There are no user contributed notes for this page.
备份地址:http://www.lvesu.com/blog/php/language.enumerations.object-differences.php