PHP Final Keywords

Final Keywords 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.

Final keyword helps us to put some constraint on classes and it’s methods. Using final keyword a class can not be inherited and a method can not be overridden.

Note: Properties cannot be declared final, only classes and methods may be declared as final.

Meaning of Final Class:

A final class is a class that cannot be extended. To declare a class as final, you need to prefix the ‘class’ keyword with ‘final’. Example below.

<?php

final class BaseClass {

public function test() {

echo “BaseClass::test() called\n”;

}

// Here it doesn’t matter if you specify the function as final or not

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)

?>

Meaning of Final Method:

A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the ‘final’ keyword. Example below:

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

?>


To seek challenging roles and to achieve excellence in the field of Open Source Web Technology with a profound spirit of commitment and dedication.

Share This Post

Related Articles

© 2017 Sumit Bansal. All rights reserved. Site Admin · Entries RSS · Comments RSS
Powered by WordPress · Designed by Theme Junkie