Final Keyword

The final keyword prevents child classes from overriding a method or constant by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

Example #1 Final methods example

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

Example #2 Final class example

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

   
// As the class is already final, the final keyword is redundant
   
final public function moreTesting() {
       echo 
"BaseClass::moreTesting() called\n";
   }
}

class 
ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Example #3 Final constants example as of PHP 8.1.0

<?php
class Foo
{
    final public const 
"foo";
}

class 
Bar extends Foo
{
    public const 
"bar";
}

// Fatal error: Bar::X cannot override final constant Foo::X
?>

Note: Properties cannot be declared final: only classes, methods, and constants (as of PHP 8.1.0) may be declared as final. As of PHP 8.0.0, private methods may not be declared final except for the constructor.

Here you can write a comment


Please enter at least 10 characters.
Loading... Please wait.
* Pflichtangabe
There are no comments available yet.

PHPUnit version 10 released

Version 10 of the popular test framework PHPUnit has been released and is available for download. ...

TheMax

Autor : TheMax
Category: Software & Web-Development

Laravel 10 published

Laravel version 10 is available for download with a minimum requirement of PHP 8.1. ...

admin

Autor : admin
Category: Software & Web-Development

DeepL Extension Write published as beta

DeepL has released a new service called "write" that aims to improve spelling and grammar with AI. ...

admin

Autor : admin
Category: Miscellaneous

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial