Search code examples
phpoopmethodsvisibilityfinal

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


Having a confusion between Private and Final in PHP.

For example I have 3 classes:

  1. Class A (parent class)
  2. Class B (child class)
  3. Class C (other class)

What I understand:

  • A: Public variables and methods are accessible to the class A, class B and class C
  • B: Private variables and methods are only accessible to the class A.
  • C: Protected variables and methods are only accessible to the class A and class B
  • D: Final methods are only accessible to the class A not to class B.

My Question is:

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

I am asking this question only for my clarification for myself.


Solution

  • Just to make it clear, the keyword final doesn't have to do anything with the visibility of a method. The visibility of a method is defined by the keywords: public, protected and private.

    The final keyword defines if another class can overwrite the method or not (if a method is final it can't be overwritten by antoher class), when the other class has access to the method. Otherwise it won't even have access to the method, so it neither can use/call the method nor overwrite it.

    Also only methods can be final it can't be used with properties.


    A, B and C are correct and as I said above the keyword final doesn't have anything to do with the visibility, so D is not correct.


    For more information see the corresponding manual pages: