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)".

 

Next chapter: Abstract >>

Previous chapter: Protected

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar