PHP Functions

When I was beginning to learn programming in Pascal, for a long time I could not fathom what functions were needed for. All my programs had flat structure without branchings or any kind. But once I ran into a problem: I had to write a program whose code looked like shown in next code.

print("Select one of the actions<BR>");

print("===========================<BR>");
print("Search <BR>");
print("===========================<BR>");

print("===========================<BR>");
print("Print <BR>");
print("===========================<BR>");

print("===========================<BR>");
print("Exit <BR>");
print("===========================<BR>");

The first line outputs a prompt and then three menu items are output. Each of them requires three lines of code. The code to output the menu items is not difficult in this case, but what if instead of three menu items I had to output 20 of them? Or what if a menu item took not 3 but 10 lines of code to output? In this case, code lines would be duplicated and the entire code would become unreadable. And can you imagine a situation in which a line for each menu item had to be changed? I would have to make 20 changes for each menu item. This would be too difficult, time-consuming, and totally inefficient.

All of this can be avoided by making use of functions. In PHP, user functions have the following format:

function Name(Parameter_1, Parameter_2, ...)
{
 Statement_1;
 Statement_2;
 ...
}

Let's consider on an example how functions work, so that you see the advantage they offer right off. The code for a function to output one menu item looks like the following:

function PrintMenu($name)
{
print("===========================<BR>");
print("$name <BR>");
print("===========================<BR>");
}

Now any time you want to output a menu item, you call this function in exactly the same way we hade called the print() function numerous times. The parameter that is passed to the function is the name of the menu item, which can be given as either variable or a simple string. Thus, to output the three menu items in the example above, the PrintMenu function is called as follows:

$mname = "Search";
PrintMenu($mname);
PrintMenu("Print");
PrintMenu("Exit");

In the first call, the parameter is the $mname, which had been set to "Search." The parameter for the other two calls is given as a string. Thus, you can pass into a function not only variables, but also values and execution results from other functions.

picture

As you can see, user-defined functions operate exactly in the same way as the PHP built-in functions. When a function is defined, parameters to be passed to it are listed in parenthesis after the function name delimited with a comma. Exactly the same number of parameters as specified in the function declaration must be passed to it when it is called.

So what is a function? As you can see from the examples, a function is a named fragment of code that can accept parameters for processing and return results. The latter capability is considered further on. A function is called by simply referencing its name. Using functions is only advantageous when they are executed repeatedly. To avoid writing the same code over and over again, such code fragments can be made into functions. Thereafter, instead of writing the same code fragment again, only one line, to call the corresponding function, has to be written.

Thus, functions allow code to be used repeatedly. For example, a script B may require a certain function that was already defined in a script A. In this case, we simply include the A script file into the B file and call the function as if it was declared in the B file. In this way, you can save on writing extra code and make your programs more readable.

Moreover, functions make code execute faster by reducing the overall code volume. The smaller a file, the less time it takes to load it, the less server memory it consumes, and the less code for the interpreter, and, ultimately, the processor, to work on. In this way, we kill not two birds with one stone, but a whole flock of them.

picture

On the other hand, functions can put a slight drag on the execution efficiency. This situation may arise when a function is called only once during script execution. If instead of the function call, the function code were used, the interpreter would execute sequentially all of its commands. But with a function call, the interpreter has to jump to another memory location, the one where the function code is stored, process the code, and then return back to the statement following the function call to continue the script execution. These extra jumps make one-time function calls slightly less efficient as compared with flat execution of the equivalent code. Nevertheless, despite this slight efficiency loss, you should not totally abstain from using one-time function calls.

Functions that consist of only one line of code can also cause performance losses. In this case, the interpreter has to make jumps for just one line of code, which could be written directly into the straight code flow.

One-line functions, however, can also be useful. They can be considered as code constants. Suppose that a certain number multiplied by number 3 has to be displayed several times throughout your program. A function to do this may look like the following:

function PrintMenu($number)
{
print($number*3);
}

At first, it may seem that it makes no sense to make one code line into a function. However, if the same operation was written directly into the program code and then you had to change one of the numbers, you could run into a problem. You would have to find all instances of this operation and do the corresponding changes. As any programmer knows, the more code you have to deal with, the more chances for something to go wrong, like failing do change one of the numbers.

Thus, functions are needed when similar code has to be executed repeatedly. It is preferable that a function contain multiple code lines. It does not mean that one code line functions should not be used, but you should not abuse using such functions. Try to use them only when there is a good chance that the code they replace can change in the future and is used in many places in scripts. Otherwise, you may consider using constants.

Let's consider some examples using functions and discuss the problems that can arise in the process. Take a look at the next code.

<HTML>
<BODY>
<?php
function print_max($number1, $number2)
{
 print ("$number1 > $number2 = ");
 
 if ($number1>$number2)
  print ("true <BR>");
 else 
  print ("false <BR>");
}

print_max(10, 435);
print_max(3240, 2335);
print_max(sdf23, 45);
print_max(45);
?>
</BODY>
<HTML>

Here we declare a function print_max().It is passed two parameters: $number1 and $number2. If the first parameter is greater than the second is, the function displays true and false otherwise.

After the function is defined, it is called four times, each time with different parameters. The first two results are what we expected them to be. But the results of the last two are really interesting, because in the third call one the parameters is a string, and in the last call only one parameter is passed to the function.

435 > 10 = true 
2335 > 3240 = false 
45 > sdf23 = true 

Warning: Missing argument 2 for print_max() in /var/www/html/1/index.php on line 10

45 > = false
picture

The second parameter in the third call is a string, because in addition to numbers it also contains letters. The PHP interpreter simply discarded the letter, using only the numbers to do the comparison. You must be away of and understand this automatic type casting feature.

The most interesting result is obtained when only one parameter is passed to the function. This made the function to issue an error message to this effect. Despite the missing second parameter, the comparison was performed. Another unexpected thing is the comparison result turned out to be false. By the conventional logic, the interpreter should have used a zero value in place of the missing second parameter. Naturally, 45 if greater than 0, so the result should have been true. But PHP has its own point of view, and you should be aware of it.

Extra parameters passed to a function will be simply discarded with a warning message to this effect displayed. The order in which parameters are passed to a function is very important. For example, the following two calls of the print_max() function will produce different results:

print_max(10, 20);
print_max(20, 10);

Even though the same numbers are passed to the function, because of the order in which they are passed, the first call will return false, and the second true.

Tag: PHP Development | Date:9/5/2009 10:42:24 AM