PHP Final Keyword Explained

  • Avinash
  • 0
  • Dec 27, 2011
  • Tutorial

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

// 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 */ } }
  // 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
      */

    }
  }

Declaring Class Method as Final

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

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 */ } }
  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
      */

    }
  }

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: