Defining & Using Functions in PHP

Functions are essential in PHP programming. PHP provides a large library of standard functions to perform basic input/output, math, and many other functions. PHP also provides the ability to define and use your own functions. PHP does not support function overloading, so when you define a function and give it a name, that name cannot be in conflict with any other function name in the standard library or any other code that you might use. Careful thought should go into the design and naming of your functions.

PHP supports both call by value and call by reference. As of PHP 5.6, vararg functions are also supported that supports arbitrary number of arguments (though earlier versions supported some vararg-like functions such as printf()). However, we will not go into detail here. Finally, another feature of PHP is that function parameters are all optional. You may invoke a function with a subset of the parameters. Depending on your PHP setup, the interpreter may issue a warning that a parameter was omitted. However, PHP allows you to define default values for optional parameters.

In general, you can define functions anywhere in your PHP script or codebase. They can even appear after code that invokes them because PHP hoists the function definitions by doing two passes of the script. However, it is good style to include function definitions at the top of your script or in a separate PHP file for organization.

Declaring Functions

In PHP, to declare a function you use the keyword function . Because PHP is dynamically typed, a function can return any type. Therefore, you do not declare the return type (just as you do not declare a variable’s type). After the function keyword you provide an identifier and parameters as the function signature. Immediately following, you provide the function body enclosed with opening/closing curly brackets. Typically, the documentation for functions is included with its declaration. Consider the following examples. In these examples we use a commenting style known as “doc comments.” This style was originally developed for Java but has since been adopted by many other languages.

 /**
  * Computes the sum of the two arguments.
  */
 function sum($a, $b) {
   return ($a + $b);
 }

 /**
  * Computes the Euclidean distance between the 2-D points,
  * (x1,y1) and (x2,y2).
  */
 function getDistance($x1, $y1, $x2, $y2) {
   $xDiff = ($x1 - $x2);
   $yDiff = ($y1 - $y2);
   return sqrt($xDiff * $xDiff + $yDiff * $yDiff);
 }

 /**
  * Computes a monthly payment for a loan with the given
  * principle at the given APR (annual percentage rate) which
  * is to be repaid over the given number of terms (usually
  * months).
  */
 function getMonthlyPayment($principle, $apr, $terms) {
   $rate = ($apr / 12.0);
   $payment = ($principle * $rate) / (1 - pow(1 + $rate, -$terms));
   return $payment;
 }

Function identifiers (names) follow similar naming rules as variables, however they do not begin with a dollar sign. Function names must begin with an alphabetic character and may contain alphanumeric characters as well as underscores. However, using modern coding conventions we usually name functions using lower camel casing. Another quirk of PHP is that function names are case insensitive. Though we declared a function, getDistance() above, it could be invoked with either getdistance(), GETDISTANCE or any other combination of uppercase/lowercase letters. However, good code will use consistent naming and your function calls should match their declaration.

The keyword return is used to specify the value that is returned to the calling function. Whatever value you end up returning is the return type of the function. Since you do not specify variable or return types, functions are usually referred to as returning a “mixed” type. You could design a function that, given one set of inputs, returns a number while another set of inputs returns a string. You can use the syntax return; to return no value (you do not use the keyword void). In practice, however, the function ends up returning null when doing this.

Calling Functions

The syntax for calling a function is to simply provide the function name followed by parentheses containing values or variables to pass to the function. Some examples:

$a = 10, $b = 20;
$c = sum($a, $b); //c contains the value 30

//invoke a function with literal values:
$dist = getDistance(0.0, 0.0, 10.0, 20.0);

//invoke a function with a combination:
$p = 1500.0;
$r = 0.05;
$monthlyPayment = getMonthlyPayment($p, $r, 60);

Passing by reference in PHP

By default, all types (including numbers, strings, etc.) are passed by value. To be able to pass arguments by reference, we need to use slightly different syntax when defining our functions.

To specify that a parameter is to be passed by reference, we place an ampersand, & in front of it in the function signature (Note: Those familiar with pointers in C will note that this is the exact opposite of the C operator.) No other syntax is necessary. When you call the function, PHP automatically takes care of the referencing/dereferencing for you.

 <?php

function swap($a, $b) {
  $t = $a;
  $a = $b;
  $b = $t;
}

function swapByRef( & $a, & $b) {
  $t = $a;
  $a = $b;
  $b = $t;
}

$x = 10;
$y = 20;

printf("x = %d, y = %d\n", $x, $y);
swap($x, $y);
printf("x = %d, y = %d\n", $x, $y);
swapByRef($x, $y);
printf("x = %d, y = %d\n", $x, $y);

?>

The first function, swap() passes both variables by value. Swapping the values only affects the copies of the parameters. The original variables $x and $y will be unaffected. In the second function, swapByRef(), both variables are passed by reference as there are ampersands in front of them. Swapping them inside the function swaps the original variables. The output to this code is as follows.

x = 10, y = 20
x = 10, y = 20
x = 20, y = 10

Observe that when we invoked the function, swapByRef($x, $y); we used the same syntax as the pass by value version. The only syntax needed to pass by reference is in the function signature itself.

Optional & Default Parameters

Parameters in PHP functions are optional. You can invoke a function without providing a subset of parameters. However, if a parameter is not provided, PHP will treat the parameter as null.

If we invoked the getDistance() function with only two parameters: getDistance(10.0, 20.0); then inside the function, $x1 and $y1 would take on the values 10 and 20, but $x2 and $y2 would be null . When used in the distance formula calculations, both would be treated as zero. If we had invoked the function with no arguments ie getDistance(); then all four parameters would be treated as null (and thus zero in the calculations).

PHP also allows you to define alternative default values for function parameters. Consider the following example:

function getMonthlyPayment($principle, $apr = 0.05, $terms = 60) {
  $rate = ($apr / 12);
  $mp = (($principle * $rate) / (1-pow(1+$rate, -$terms)));
  return round($mp * 100) / 100;
}

In this example, the second and third parameter have been given default values of 0.05 and 60 respectively. If a call to this function omits these parameters, they are not treated as null, but take on these defaults instead.

 $x = getMonthlyPayment(10000, 0.07, 72);
 print $x."\n"; //170.49

 //terms will be 60
 $x = getMonthlyPayment(10000, 0.07);
 print $x."\n"; //198.01

 //apr will be 0.05, terms will be 60
 $x = getMonthlyPayment(10000);
 print $x."\n"; //188.71

 //balance will be null (0), apr will be 0.05, terms will be 60
 $x = getMonthlyPayment();
 print $x . "\n"; //0 but also a warning

It would not be possible to invoke getMonthlyPayment() by omitting only the second argument. Providing n arguments will match the first n parameters. Thus, in your function design you should place any optional/default parameters last.

Function Pointers

Functions are just pieces of code that reside somewhere in memory just as variables do. Since we can pass variables by reference, it also makes sense that we would do the same with functions.

In PHP, functions are first-class citizens2 meaning that you can assign a function to a variable just as you would a numeric value. For example, you can do the following:

$func = swapByRef;

$func($x, $y);

In the example above, we assigned the function swapByRef() to the variable $func by using its identifier. The variable essentially holds a reference to the swapByRef() function. Since it refers to a function, we can also invoke the function using the variable as in the last line. This allows you to treat functions as callbacks to other functions.


Licenses and Attributions


Speak Your Mind