6.7.4 FinalThis is NOT the latest copy of this book; click here for the latest version.
The final keyword is used to declare that a function or class cannot be overriden by a sub-class. This is another way of stopping other programmers using your code outside the bounds you had planned for it.
Take a look at the following code:
class dog {
private $Name;
private $DogTag;
final public function bark() {
print "Woof!\n";
}
The dog bark() function is now declared as being final, which means it cannot be overridden in a child class. If we have bark() redefined in the poodle class, PHP outputs a fatal error message: Cannot override final method dog::bark(). Using the final keyword is entirely optional, but it makes your life easier by acting as a safeguard against people overriding a function you believe should be permanent.
For stronger protection, the final keyword can also be used to declare a class as uninheritable - that is, that programmers cannot extend another class from it. Take a look at this script:
<?php
final class dog {
public $Name;
private function getName() {
return $this->Name;
}
}
class poodle extends dog {
public function bark() {
print "'Woof', says " . $this->getName();
}
} ?>
Attempting to run that script will result in a fatal error, with the message "Class poodle may not inherit from final class (dog)".
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|