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

Having confusion between Private

and Final

in PHP.

For example, I have 3 classes:

  • Class A (parent class)
  • Class B (child class)
  • Class C (different class)

What I understand:

  • A: Shared variables and methods are available for class A, class B and class C
  • B: Private variables and methods are only available to class A.
  • C: Protected variables and methods are only available for class A and class B
  • D: Finite methods are only available to class A, not class B.

My question is:

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

I am asking this question just for my clarification to myself.

+3


source to share


3 answers


To be clear, the keyword final

shouldn't do anything with the visibility of the method. Visibility is determined by the method of key words public

, protected

and private

.

The final keyword determines whether another class can overwrite a method or not (if this method is final, it cannot be overwritten by the antoher class) when another class has access to that method. Otherwise it won't even get access to the method, so it cannot use / call the method and not overwrite it.

Also, only methods that cannot be used with properties can be final.




A, B, and C are all correct, and as I said above, the final keyword has nothing to do with visibility, so D is wrong.


For more information, see the relevant man pages:

+3


source


Final classes or methods may NOT be overridden.

From php doc

PHP 5 introduces a final keyword that prevents child classes from overriding a method, prefixing the definition with final. If the class itself is determined to be final, it cannot be extended.



Example from php documentation:

<?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()
?>

      

More details: http://php.net/manual/en/language.oop5.final.php

+1


source


A final

method property is used to make it clear to the compiler that a given method cannot be overridden elsewhere.

As a result, if we declare a function as final

, and then we try to override it somewhere else, we get warning

or fatal error

.

0


source







All Articles