PHP Static And Final

static & final in php

The static Keyword

PHP Static And Final : The PHP static keyword defines static properties and static methods.A static property/method of a class can be accessed without creating an object of that class.

A static property or method is accessed by using the scope resolution operator :: between the class name and the property/method name.


Example :

<?php

class myClass {

  static $myStaticProperty = 42;

}



echo myClass::$myStaticProperty;

?>

Example :

<?php

class myClass {

  static $myProperty = 42;

  static function myMethod() {

    echo self::$myProperty;

  }

}



myClass::myMethod();

?>

The final Keyword

The PHP final keyword defines methods that cannot be overridden in child classes. Classes that are defined final cannot be inherited.

Example :

<?php

class myClass {

  final function myFunction() {

    echo "Parent";

  }

}

// ERROR because a final method cannot be overridden in child classes.

class myClass2 extends myClass {

  function myFunction() {

    echo "Child";

  }

}

Spread the love

Leave a Comment

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