Final

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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Abstract >>

Previous chapter: Protected

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.