关键字 'Private' 和 'Final' 有什么区别?

What is the difference between the keyword 'Private' and 'Final'?

在 PHP 中混淆了 PrivateFinal

例如我有 3 个 classes:

  1. Class一个(parentclass)
  2. Class B (child class)
  3. ClassC(其他class)

我的理解:

我的问题是:

After using private we can achieve functionality like final then why we use final?

我问这个问题只是为了澄清我自己。

一个方法的属性 final是用来让编译器明白给定的方法不能在别处被重写。

因此,如果我们将函数声明为 final,然后我们尝试在其他地方覆盖它,我们将得到 warningfatal error

Final 类 或方法可以 NOT 被覆盖。

来自 php 文档

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

php 文档中的示例:

<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

更多详情:http://php.net/manual/en/language.oop5.final.php

为了清楚起见,关键字 final 与方法的可见性无关。方法的可见性由关键字定义:publicprotectedprivate.

final 关键字定义另一个 class 是否可以覆盖该方法(如果一个方法是 final 则它不能被另一个 class 覆盖),当另一个 class 可以访问该方法。否则它甚至无法访问该方法,因此它既不能 use/call 该方法也不能覆盖它。

此外,只有方法可以是最终的,它不能与属性一起使用。


A、B 和 C 是正确的,正如我上面所说的关键字 final 与可见性没有任何关系,所以 D 是不正确的。


有关详细信息,请参阅相应的手册页: