I recently posted an article on how to create reusable menus for a website with php and CSS. Although it’s a perfectly valid method to create reusable menus, I couldn’t help but being unsatisfied with the use of global variables and the include of one file per menu.

So I decided to find a better way, and this is what I’m going to show you here today. The idea is to get rid of the global variable and the include and instead pass a parameter to a function.

Using the same menu as in the previous article, our html page would look like this to display the menu with the “FAQ” option selected.

  require_once($_SERVER['DOCUMENT_ROOT'] . "/includes/menu.php");

It might not look like such a great improvement, but it is because now we can place a lot of code in the menu.php, not just the code for one specific menu. Now we can add more menu functions in menu.php and centralize all the menus in one place. This will greatly simplify all the pages using menus.

Before we look at the new version of menu.php, there is something else that I’m not too happy about. It would be much better to use a constant rather than the “FAQ” string for the function parameter. It provides stronger typing and can prevent errors due to typos, plus we’re going to use the constant to simplify the code even move in menu.php.

So our call to the menu looks like this:

  require_once($_SERVER['DOCUMENT_ROOT'] . "/includes/menu.php");
  Display_Menu( MENU_OPTION::FAQ );

Now let’s look at our new version of menu.php. The html code to produce menus is now wrapped into functions, and we have a new class called MENU_OPTION to define our constants.

// *************************************************
// Class MENU_OPTION: Constants for menu items
// *************************************************
 // Top Menu
 const HOME  = 1;
 const FAQ   = 2;
 const ABOUT = 3;

// Display Menu
// *************************************************
function Display_Menu($selected_option = 0)
  // Array containing the "active" words
  $active_class = array(NULL,NULL,NULL);

  // The "active" word is now placed in the appropriate cell
  // in one line of code thanks to the constants
  if ($selected_option > 0)
    $active_class[$selected_option-1] = "active";

// Build HTML menu code with the dynamically generated from the array
echo <<<EOD
  <div id="top-menu">
    <li><a href="/home.html" class="{$active_class[0]}">Home</a></li>
    <li><a href="/faq.html" class="{$active_class[1]}">FAQ</a></li>
    <li><a href="/about.html" class="{$active_class[2]}">About</a></li>

As you can see the code in menu.php is much neater and smaller. Also we can now add more menus and place the related functions in the same file.

You can see it in action on my website: