PHP Final Classes and Methods- Tutorialpath

PHP Final Class
PHP Final Class

Final classes

Inheritance allows for enormous flexibility within a class hierarchy. You can create sub-classes to extend the functionality of a base class, but PHP OOP gives the possibility to create classes that cannot be extended. Such a class is called final class.

A final class is declared by adding the final keyword before the class word.

Example:

final class Example
final class Example

Output:

final class output
final class output

 

Final methods

A normal method (public or protected) can be overridden in the child class. If you want a method to remain fixed and unchanging, prefix the definition with the final keyword.

A final method cannot be overridden.

Example:

final method Example
final method Example

Output:

final method output
final method output

Use of Final Keyword:

  • The Final keyword prevents child classes from overriding and method.
  • It means we define a method with final then it prevents us to over ride the method.

 

Leave a Reply

Your email address will not be published. Required fields are marked *