CodingBison

PHP functions are an important building block of PHP. Functions offer several key advantages in terms of code modularity, code reuse, behavior consistency, and easy debuggability. It is worth understanding each of these advantages!

Code Modularity: functions allow a programmer to develop modular code; each function can contain a set of code that typically does one specific task (or a set of closely related tasks). This way, functions can provide a clear partitioning of the application logic.

Code reuse: functions promote code-reuse. Different parts of program may need to do the same task (or tasks). With a common function, all these parts have to do is simply call that function.

Behavior consistency: functions promote consistency in behavior. When different callers invoke the same function, then the same lines of code are run and all callers see the same behavior. On the other hand, if the same task were to be implemented at different locations, then, over time new programmers can modify/update lines of code in one place and forget to update in other places.

Easy debuggability: if we need to debug a particular task (using printf or using a GDB breakpoint) and since all calls for the task use a common function, it becomes easier to put the debugging infrastructure (printf or GDB breakpoints) in one function.

Now that we have described the usefulness of functions, let us understand two key properties of functions: arguments and returns values.

When we call a function, we can pass a set of variables (known as arguments) to the function. A function can take any number of arguments (including zero) and uses these arguments (if any) as an input to its logic. Once it completes its computation, it can return the computed value back to the caller. This value is referred to as return value. Once again, it is not necessary for a function to return any value!

When defining a function, we must put the keyword "function" before its name. In addition, Python function names do not have a "$" sign in front of it!.

Variables defined within the function block have a different scope. Due to this scope, we cannot access variables defined outside the function and vice-versa. However, if we must access variables defined outside of the function within the function, then we can do so by using the "global" keyword before the variable.

Unlike some other languages (such as C), we do not have to declare the function first -- we can right away define it (which means provide the entire body of the function) and start using it. Likewise, we do not need to specify the return type of the function as well.

Next, let us look at some examples that implement functions.

Our first example (provided below) implements a function to retrieve the year of birth for a given user: get_birth_year(). This function takes one argument ("name") and returns the year of birth after matching the passed name to that of existing users. This program uses a 2-dimensional global array, where each record has a username and the date of birth (we will cover more of multi-dimensional array in subsequent pages).

 <?php
 /* Names of users who have signed up for the application */
 $username_array[] = array("James Fulton", 1980);
 $username_array[] = array("Thomas Kipling", 1970);
 $username_array[] = array("Karuna Simon", 1965);
 $username_array[] = array("Lilly Sellers", 1982);
 $username_array[] = array("Homer Simpson", 1955);

 function get_birth_year($name) {
     global $username_array;
     for ($counter=0; $counter < 5; $counter++) {
         if ($username_array[$counter][0] == $name) {
             return $username_array[$counter][1]; 
         }
     }
     return -1;
 }

 $birth_year = get_birth_year("Homer Simpson"); 
 if ($birth_year != -1) {
     echo "Homer Simpson was born in $birth_year <br>";
 } else {
     echo "We do not have a record for Homer Simpson <br>";
 }

 $birth_year = get_birth_year("Marge Simpson"); 
 if ($birth_year != -1) {
     echo "Marge Simpson was born in $birth_year <br>";
 } else {
     echo "We do not have a record for Marge Simpson <br>";
 }
 ?>

From the output (provided below), we can see that we can call the same function multiple times by passing different arguments each time.

 Homer Simpson was born in 1955
 We do not have a record for Marge Simpson

As noted earlier, a function does not necessarily have to return anything (same as returning a void!). Our second example is a modified implementation of the previous program. This example moves the task of retrieving and printing the year of birth from the main program to the get_birth_year() function itself. Now, this function does not need to return any integer. The output in this case is exactly the same as before and hence we omit it.

 <?php
 /* Names of users who have signed up for the application */
 $username_array[] = array("James Fulton", 1980);
 $username_array[] = array("Thomas Kipling", 1970);
 $username_array[] = array("Karuna Simon", 1965);
 $username_array[] = array("Lilly Sellers", 1982);
 $username_array[] = array("Homer Simpson", 1955);

 function get_birth_year($name) {
     global $username_array;
     for ($counter=0; $counter < 5; $counter++) {
         if ($username_array[$counter][0] == $name) {
             $birth_year = $username_array[$counter][1];
             echo "$name was born in $birth_year <br>";
             return;
         }   
     }   
     echo "We do not have a record for $name<br>";
 }

 get_birth_year("Homer Simpson"); 
 get_birth_year("Marge Simpson"); 

 ?>

Recursive Functions

Functions are so versatile that they can even call themselves! Such a class of functions are known as recursive functions.

Recursive functions typically process a series of data. They start with the first data of the series, and then calls themselves to process the next data in the series, and so on. These functions calling themselves until they reach the end of the series. At each call, the remaining series is passed as the argument to the next call of the same function.

Let us demonstrate a simple recursive function by computing factorial of a number. The factorial of a number, N is defined as (N * (N-1) * (N-2) *..... * 3 * 2 * 1). Thus, factorial of 6 would be 6 * 5 * 4 * 3 * 2 * 1 = 720.

Here is a trivial program that uses a recursive function to compute the factorial of 6. The function compute_factorial() calls itself recursively to compute factorial of 6.

 <?php
 function compute_factorial($num) {
     $factorial = 1;  

     echo "computing factorial for $num <br>";
     if ($num == 1) { 
         return $factorial;
     }        
     $factorial = $num * compute_factorial($num-1);
     return $factorial;
 }

 $factorial_value = compute_factorial(6);
 echo "The factorial of 6 is $factorial_value <br>";
 ?>

The output shows how the function calls itself for all the integers starting from 6 to 1.

 computing factorial for 6
 computing factorial for 5
 computing factorial for 4
 computing factorial for 3
 computing factorial for 2
 computing factorial for 1
 The factorial of 6 is 720

Print Functions

Almost all the examples so far have used "echo" to print the output. This section provides a brief discussion of the additional print functions like print, printf, print_r, var_dump, and die.

The function print() is similar to that of echo. It takes one string input as an argument and prints it to the HTML page. Thus, "print("Hello World!\n");" is same as "echo "Hello World!\n";"

The next function, printf(), takes a formatted input of string. This function takes a main string followed by a list of argument. These arguments replace input identifiers like %d or %f provided in the main string. Thus, "printf("This is a trial: %d \n", 100);" evaluates to "This is a trial: 100 \n" because printf replaces "%d" identifier with the value of 100.

Besides %d, printf() supports several additional types: (a) %e or %E or %f for float numbers (fractional numbers), (b) %x and %X for hexadecimal (the upper case prints hexadecimal numbers in upper case), (c) %U for unsigned numbers float, (d) %O for octal, (e) %C for characters, and (f) %s for strings. If we have to print the "%" character itself, then we can use "%%"; here, the first "%" acts as an escape character.

We can also specify additional parameters to the "%" operator. For floats, a value of "%.4f" means that we should print 4 decimal values. If the input has additional decimal values, then PHP would truncate it. We can also specify padding (the total characters for the output); for example, "%10d" means that the total output character would be 10. By default, padding is done on the left side. To do padding on the right side, we can specify this parameter as a negative value. Thus, "%-10d" means that we need to do padding on the right side.

The next two print functions are print_r() and var_dump(). These functions take into account the nature of data being printed and allow us to easily print even arrays. var_dump() also prints the type and size of the variables being printed.

The last print function, "die()" is a special case of a print function and is used when the program runs into an error condition. In the event of an error, we can use "die()" to first print an error message and then to exit the program. For example, "die("Failed to Connect to the server")" would first print the error message "Failed to Connect to the server" and then exit the program.

Here is an example that provides usage for all of these print functions:

 <?php
 $var1 = 10; 
 $var2 = 30; 

 $sum = $var1 + $var2;
 echo "(echo) Sum is $sum <br>";
 print("(print) Sum is $sum <br>");
 printf("(printf) Sum is %d <br>", $sum);
 echo "(print_r) Sum is ";
 print_r($sum);
 echo "<br>(var_dump) Sum is ";
 print_r($sum);

 $username_array[] = "James Fulton";
 $username_array[] = "Thomas Kipling";
 $username_array[] = "Karuna Simon";
 $username_array[] = "Lilly Sellers";
 $username_array[] = "Homer Simpson";

 echo "<br>Using print_r:<br>";
 print_r($username_array);

 echo "<br><br>Using var_dump:<br>";
 var_dump($username_array);

 echo "<br><br>Using die::<br>";
 die("<br><br>Done running the program. Time to quit.<br>");
 ?>

Here is the output for the above program:

 (echo) Sum is 40
 (print) Sum is 40
 (printf) Sum is 40
 (print_r) Sum is 40
 (var_dump) Sum is 40

 Using print_r:
 Array ( [0] => James Fulton [1] => Thomas Kipling [2] => Karuna Simon 
     [3] => Lilly Sellers [4] => Homer Simpson )

 Using var_dump:
 array(5) { [0]=> string(12) "James Fulton" [1]=> string(14) "Thomas Kipling" 
     [2]=> string(12) "Karuna Simon" [3]=> string(13) "Lilly Sellers" 
     [4]=> string(13) "Homer Simpson" } 

 Using die:
 Done running the program. Time to quit.




comments powered by Disqus