gpt4 book ai didi

php - 什么时候在 PHP 中使用 Final?

转载 作者:IT王子 更新时间:2023-10-29 00:42:04 27 4
gpt4 key购买 nike

我知道 Final 类的定义是什么,但我想知道如何以及何时真正需要 final。

<?php
final class Foo extends Bar
{
public function()
{
echo 'John Doe';
}
}

如果我理解正确,“final”可以扩展“Foo”。

谁能解释什么时候以及为什么应该使用“final”?换句话说,有什么理由不应该扩展一个类?

例如,如果类“Bar”和类“Foo”缺少某些功能,那么创建一个扩展“Bar”的类会很好。

最佳答案

关于 "When to declare classes final" 有一篇不错的文章.其中的一些引述:

TL;DR: Make your classes always final, if they implement an interface, and no other public methods are defined

Why do I have to use final?

  1. Preventing massive inheritance chain of doom
  2. Encouraging composition
  3. Force the developer to think about user public API
  4. Force the developer to shrink an object's public API
  5. A final class can always be made extensible
  6. extends breaks encapsulation
  7. You don't need that flexibility
  8. You are free to change the code

When to avoid final:

Final classes only work effectively under following assumptions:

  1. There is an abstraction (interface) that the final class implements
  2. All of the public API of the final class is part of that interface

If one of these two pre-conditions is missing, then you will likely reach a point in time when you will make the class extensible, as your code is not truly relying on abstractions.

附言感谢@ocramius 的精彩阅读!

关于php - 什么时候在 PHP 中使用 Final?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4248021/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com