Tutorial

PHP Final Keyword Explained

PHP 5 introduced lots of new things in Object Oriented Programming. Final keyword is one of the feature introduces in PHP 5.

What is Final Keyword?

In PHP, Final Keyword is applicable to only class and class methods. We can not declare variables as Final in PHP.

So if you declare class method as a Final then that method can not be override by the child class. Same as method if we declare class as a Final then that class can not be extended any more.

How to Use Final Keyword?

This can be used with the keyword [code]Final[/code]. Here are two examples which shows the use of Final Keyword with methods and class itself.

Note: We can not declare variables as Final in PHP.

Declaring Class as Final

Below code will end up with this error: Class child_class may not inherit from final class (parent_class)

[cc lang=”php”]
// This class can not be Extended
final class parent_class
{
public function class_method()
{
/*
Code Here
*/
}
}

class child_class extends parent_class
{
public function class_method()
{
/*
Code Here
*/
}
}

[/cc]

Declaring Class Method as Final

Below code will end up with this error: Cannot override final method parent_class::class_method()

[cc lang=”php”]

class parent_class
{
// We Can not override this method
// As it declared as final
final public function class_method()
{
/*
Code Here
*/
}
}

class child_class extends parent_class
{
public function class_method()
{
/*
Code Here
*/
}
}

[/cc]

Shares:

Leave a Reply

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