[ Team LiB ] Previous Section Next Section

Final Methods

Sometimes, you do not want subclasses to be able to override methods that you define or implement. Perhaps the functionality you define there is exactly the way things should be:


class Item {
  private $id = 555;
  final function getID() {
    return $this->id;
  }
}

By declaring the getID() method final in this example, we ensure that any attempt to override it in a subclass will cause an error. Notice the following code:


class PriceItem extends Item {
  function getID() {
    return 0;
  }
}

It generates the following error:


Fatal error: Cannot override final method item::getid()

On the whole, you should use final sparingly. Your class might fit uses that you do not yet know about, and flexibility is worth maintaining.

    [ Team LiB ] Previous Section Next Section