Static and Final

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Static
We can't call methods or properties of a class without an instance of that class unless the method or property is declares as static. static keyword is used to make a property or method available without the instance.

Scope Resolution Operator(::)
With scope resolution operator you can access staic methods or properties of class without an instance of that class (classname::method() / classname::$property).
Scope resolution operator is also used to access constants and overridden methods or properties of the parent class in the child class using parent:: .

<?php
class sample{
	static $key = "Static property<br>";
	static function test(){
		echo "Static method";
	}
}
echo sample::$key;
sample::test();
?>


Output
Static property
Static method

Final
final keyword is used to prevent overriding of a parent class method/function in the child class. You can declare a method final in parent class and trying to override that method in child class will give a fatal error.

<?php
class sample{

	final function test(){
		echo "Method from parent class<br>";
	}
}
class new_sample extends sample{
	function test(){
		echo "From child class";
	}
}
?>


Output

Fatal error: Cannot override final method sample::test() in C:\xampp\htdocs\test.php on line 12

Login to Track Your Progress