Home > Articles > Programming > PHP

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

Creating a Function

In articles 1 and 2, we made use of functions that are predefined as part of PHP. For example, to find out how many days were in the month we were displaying, we simply wrote

$numberofdays = cal_days_in_month(CALENDAR_GREGORIAN, $month, $year);

In this case, the function cal_days_in_month() took three arguments (CALENDAR_GREGORIAN, $month, and $year) and returned an integer value, which was assigned to the variable $numberofdays.

We can create our own functions in a PHP page by simply declaring them as a function and including code within brackets ({}), as shown in Listing 1.

Listing 1—Adding Functions to calendar.php

...
  <input type="submit" value="Display Calendar" />
</form>
<?php

function get_current_month(){

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

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

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

  if (!isset($g_month)){
    $month = get_current_month();
    $year = get_current_year();
  } else {
    $month = $g_month;
    $year = $g_year;
  }
...

In this case, we created two functions, get_current_month() and get_current_year(), which we're then calling in situations in which no month was submitted with the form. Each function performs its actions and then returns a value, which is taken by a variable. A function can contain any valid PHP code, including classes and other functions.

In this case, neither function takes an argument, but it is possible to pass information in to the function in that way, as we'll see next.

  • + Share This
  • 🔖 Save To Your Account