我意识到这个问题已经在其他地方针对不同的编程语言提出过...但这不是 PHP 领域中相同答案的 100% 指标,所以我问这个问题。
谁能告诉我“final static”和“const”之间的区别,特别是在 PHP 中?
最佳答案
最终
方法或类不能被子类修改。这可以防止类继承、方法覆盖和/或方法的重新定义。
Only class definitions and/or methods inside a class can be defined as
final
.
静态
将类方法 或属性 声明为静态值,以便您无需实例化对象即可访问它们。这些在父类和子类之间共享。
A class definition can not be
static
unlikefinal
.
常量
这些为类创建了一个常量值。常量值将被更改,并且不能通过父类或子类中的方法更改。
Class constants are allocated per instance of the class.
const
本身就是一个类型说明符。不能和public
/private
/static
等放在一起,final
,前面说的可以用连同任何方法或类定义,因此;适用于所有这些。 static
不能应用于类定义,但可用于类属性。
更新
modifiers自 PHP 7.1.0 起允许用于类常量。
class Foo { public const bar = 5; private const baz = 6; }
To summarise,
final static
can not be used to define something like:class X { final static x = 5; }
which is why you have a
const
.
关于php - 在 PHP 中, "final static"和 "const"有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19473528/