什么时候在 PHP 中使用 Final?
我知道 Final 类的定义是什么,但我想知道如何以及何时真正需要 Final 。
<?php
final class Foo extends Bar
{
public function()
{
echo 'John Doe';
}
}
如果我理解正确的话,“final”使其能够扩展“Foo”。
谁能解释何时以及为什么应该使用“最终”?换句话说,有什么理由不应该延长班级吗?
例如,如果类“Bar”和类“Foo”缺少某些功能,那么创建一个扩展“Bar”的类会很好。
I know what the definition is of a Final class, but I want to know how and when final is really needed.
<?php
final class Foo extends Bar
{
public function()
{
echo 'John Doe';
}
}
If I understand it correctly, 'final' enables it to extend 'Foo'.
Can anyone explain when and why 'final' should be used? In other words, is there any reason why a class should not be extended?
If for example class 'Bar' and class 'Foo' are missing some functionality, it would be nice to create a class which extends 'Bar'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有一篇关于“何时声明类为final”的好文章。摘录几段:
PS 感谢@ocramius 的精彩阅读!
There is a nice article about "When to declare classes final". A few quotes from it:
P.S. Thanks to @ocramius for great reading!
对于一般用途,我建议不要创建类
final
。可能在某些用例中它是有意义的:如果您设计一个复杂的 API/框架,并希望确保框架的用户只能覆盖您希望他们控制的功能部分,那么您可能会这样做限制这种可能性并将某些基类设为final
。例如,如果您有一个
Integer
类,那么将其设为final
可能是有意义的,以便让框架的用户能够覆盖add(. ..)
类中的方法。For general usage, I would recommend against making a class
final
. There might be some use cases where it makes sense: if you design a complex API / framework and want to make sure that users of your framework can override only the parts of the functionality that you want them to control it might make sense for you to restrict this possibility and make certain base classesfinal
.e.g. if you have an
Integer
class, it might make sense to make thatfinal
in order to keep users of your framework form overriding, say, theadd(...)
method in your class.原因是:
—— 引自 David Powers 的PHP Object-Oriented Solutions一书的第 68 页。
例如:
这涵盖了整个类,包括它的所有方法和属性。现在,任何从 childClassname 创建子类的尝试都会导致致命错误。
但是,如果您需要允许类被子类化但防止特定方法被重写,则final关键字位于方法定义之前。
在此示例中,它们都无法重写
PageCount()
方法。The reason are:
—— quoted from page 68 of the book PHP Object-Oriented Solutions by David Powers.
For example:
This covers the whole class, including all its methods and properties. Any attempt to create a child class from childClassname would now result in a fatal error.
But,if you need to allow the class to be subclassed but prevent a particular method from being overridden, the final keyword goes in front of the method definition.
In this example, none of them will be able to overridden the
PageCount()
method.final
类是无法扩展的 http: //php.net/manual/en/language.oop5.final.php您可以在类包含您特别不希望覆盖的方法的地方使用它。这可能是因为这样做会以某种方式破坏您的应用程序。
A
final
class is one which cannot be extended http://php.net/manual/en/language.oop5.final.phpYou would use it where the class contained methods which you specifically do not want overridden. This may be because doing do would break your application in some way.
我的 2 美分:
何时使用
final
:为什么?
来解决使用它的坏原因:
My 2 cents:
When To Use
final
:Why?
Bad Reasons to Use It: