Home > Articles > Programming > PHP

  • Print
  • + Share This
Like this article? We recommend

Functions and Scope

A function doesn't actually have to return a value. Instead, it can take information and use it to perform an action. (In other languages, this might be called a procedure or a subroutine.) For example, we can create a function that simply sets the $month and $year variables based on the values submitted with the form, as shown in Listing 2.

Listing 2—Functions that Don't Return a Value

...
function get_current_month(){

    $today = getdate(); 
    return $today['mon']; 
}

function get_current_year(){
    $today = getdate(); 
    return $today['year']; 
}

function set_month ($submittedMonth){

  global $month;

  if (!isset($submittedMonth)) {

    $month = get_current_month();

  } else {

    if ((intval($submittedMonth) > 0) && (intval($submittedMonth) <= 12)) {
     $month = $submittedMonth;
    } else {
     $month = get_current_month();
    }
  }

}

function set_year ($submittedYear) {

  global $year;

  if (!isset($submittedYear)) {

    $year = get_current_year();

  } else {

    if (intval($submittedYear) == $submittedYear) {
     $year = $submittedYear;
    } else {
     $year = get_current_year();
    }
  }
}

  //Initialize variables
  import_request_variables('pgc', 'g_');

  set_month($g_month);
  set_year($g_year);
...

Looking at set_month() in particular, we see that it takes a single argument, $submittedMonth, which is populated with the value of $g_month when the page calls set_month($g_month). The function then tests $submittedMonth to make sure that it's actually set. In other words, was a value of $g_month submitted with the form? And if it is, is it a positive integer less than or equal to 12? If either one of those tests fails, the function sets the value of $month by calling our previous function, get_current_month(). If neither test fails, the function sets the value to $submittedMonth.

In both cases, the function simply sets the value of the $month variable, but that's not quite the end of the story. Each function has its own scope, meaning that a variable declared within the function exists only within that function. For example, $submittedMonth has no value outside the function.

As a side effect of this behavior, if we simply referenced the $month variable within the function, we would set the value not of the main $month variable used by the rest of the application, but of a separate $month variable that exists only within the function.

To combat this, we can use the global keyword to tell the function to use the $month variable from the main application, rather than creating its own version.

Now we're ready to look at adding functions to classes.

  • + Share This
  • 🔖 Save To Your Account