Final keyword

Final keyword in Php

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 by child class.
Note:-
we can not declare variable as final (In Php we use const keyword instead of final keyword for variable but in Java we use final keyword for variable).

Syntax of final keyword for class:-
final class classname{
}

Syntax of final keyword for method:-
final function functionname(){
}

final class

A final class is a class that cannot be extended.
Example:- In this below eg. we create a two classes first class communication which is define as final and second class is Indian which is extended to communication class because communication is a final class so it can not be extended so system generate a compile error.


<?php 
final class communication {
public function language()
{
	return 'speak usually Hindi language.';
}
}
class Indian extends communication{
public function showInformation() {
	echo $this->language();
}
}
$ind_obj=new Indian;
$ind_obj->showInformation();
?>

the compiler will throw a compile error.

Output:- Fatal error: Class Indian may not inherit from final class (communication)

final method

A final method is a method that cannot be overridden.
Example:- In the below eg. language method is define as a final in the communication class and same method name is define in the Indian class so when call this method of the Indian class then system generate compile error.


<?php 
class communication {
	final public function language() {
		return 'speak usually Hindi language.';
	}
}
class Indian extends communication {

	public function language() {
		return 'speak usually English language.';
	}
        public function showInformation() {
		echo $this -> language();
	}
}

$ind_obj = new Indian;
$ind_obj -> showInformation();
?>

In this case the compiler causes a compile error.

Output:- Fatal error: Cannot override final method communication::language()

Is Final Method inherited?

Final method can be inherited but not override in child class.
Example:-


<?php 
class communication {
	final public function language() {
		return 'speak usually Hindi language.';
	}

}

class Indian extends communication {

	public function people() {
		return 'Indian people ';
	}

	public function showInformation() {
		echo $this -> people() . $this -> language();
	}

}

$ind_obj = new Indian;
$ind_obj -> showInformation();
?>
Output:- Indian people speak usually Hindi language.