PHP5 “final” Keyword By Will Fitch 19 May 2006 at 2:14 pm

PHP5 has introduced many new features for object-oriented programming. One of those misunderstood, useful keywords is the ?final? keyword.

The final keyword allows us to do three things:

  1. It prevents child classes from overriding a method
  2. It prevents a class from being extended if the class is marked “final”
  3. Serves as a reminder to future developers of your code that the class has a purpose, and should not be messed with further

Don’t get me wrong, this keyword can be abused as with all other aspects of code. Just becuase you have finished writing a class, it doesn’t mean that you should mark it as final.

The true purpose of the “final” keyword is to simply protect methods or classes that are not meant to be modified or extended. For instance, you have a method that has 3 parameters. This method is used heavily throughout your application, and in the instance that it breaks, your application is rendered virtually useless. What could cause this type of situation?

Take this example:

PHP
  1. <?php
  2. public function createDropdown($select_name,$arr_values,$default_value=null) {
  3. $select =
  4. <select id="’.$select_name.‘" name="’.$select_name.‘">’; foreach ($arr_values as $key=>$value) { if (!is_null($default_value)) { if ($default_value == $key) $selected = ‘ selected’; else $selected = ; } else { $selected = ; } $select .= ‘<option value="’.$key.‘">’.$value.‘</option>’; } $select .= ‘</select>
  5. ;
  6. return $select;
  7. }
  8. ?>

This method creates an HTML select menu and allows for a default value. However, John want’s extend the class, and add a paramter between $select_name and $arr_values that allows for an onchange. Even with a default value this will cause issues with the previous usage of this method. To protect it, simply put the “final” keyword before the access control keyword:

PHP
  1. <?php
  2. final public function createDropdown($select_name,$arr_values,$default_value=null) {
  3. $select =
  4. <select id="’.$select_name.‘" name="’.$select_name.‘">’; foreach ($arr_values as $key=>$value) { if (!is_null($default_value)) { if ($default_value == $key) $selected = ‘ selected’; else $selected = ; } else { $selected = ; } $select .= ‘<option value="’.$key.‘">’.$value.‘</option>’; } $select .= ‘</select>
  5. ;
  6. return $select;
  7. }
  8. ?>

It’s that simple. PHP is simply giving you more actions to take to protect your code!

[del.icio.us] [Digg] [dzone] [Furl] [Google] [Reddit] [Slashdot] [Sphere] [Yahoo!]

Leave a Reply