Wednesday, July 16, 2014

Final keyword in PHP

If we declare a function inside a class as final, we cannot use that function name in its derived classes. That is final keyword avoid method overriding. You can see more about method overriding here.

Example 1:
<?php
class A
{
     final function test()                // Declare function as final.
     {
          echo 'From base class';
     }
}

class B extends A
{
      function test()                      // Will throw an error.
      {
            echo 'This never run.';
      }
}
?>

And we can also avoid extending a class by declaring a class as final.

Example 2:
final class A                               // Declare class as final.
{
     function fun()
     {
     }
}

class B extends A                      // Will throw an error.
{
}

And note we can only declare function and class as final, cannot declare variable as final.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...