Final
The final keyword is used to declare that a method or class cannot be overridden by a subclass. For example:
class A {
private $Name;
private $ATag;
final public function say( ) {
print "Hello!\n";
}
// Statement here.
The A say( ) method is now declared final, which means it cannot be overridden in a child class. If we have say( ) redefined in the B class, PHP outputs a fatal error message: "Cannot override final method A::say( )". Using the final keyword is optional, but it makes your life easier by acting as a safeguard against people overriding a method you believe should be permanent.
For stronger protection, the 'final' keyword can also be used to declare a class uninheritable that is, that programmers cannot extend another class from it. For example:
Ex. --> final class A {
private $Name;
public function getName( ) {
return $this->Name;
}
}
class B extends A {
public function say( ) {
print "'Hello', says " . $this->getName( );
}
}
Attempting to run that script will result in a fatal error, with the message: "Class B may not inherit from final class (A)".
0 comments:
Post a Comment