Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of "Final" keyword in php

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 109
    Comment on it

    This tutorial will help us to see the use of final keyword with a method of a class and a class individually.

    Example:

    class parentClass {
    
       public function test1() {
           echo "This is test1 method of parentClass";
       }
    
       final public function test2() {
           echo "This is test2 method of parentClass that is made final";
       }
    }
    
    OUTPUT: 
    $obj = new parentClass();
    $obj->test2();
    
    //This is test2 method of parentClass that is made final 
    

    // But when we extend the parentClass

    class childClass extends parentClass { public function test2() { echo "on overriding the final method test2 a fatal error will be thrown "; } }

    OUTPUT: It gives a Fatal error


    When we make a class final

    final class parentClass {
       public function test1() {
           echo "This is test1 method of parentClass";
       }
    
    
       public function test2() {
           echo "This is test2 method of parentClass";
       }
    }
    
    
    class ChildClass extends parentClass {
    
    }
    
    Here we get a Fatal error as we cannot extend the final class.
    

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: