Developer

Script Teez: Writing functions in PHP

In this month's Script Teez, Vincent Danen takes a look at something very important for both its timesaving benefits and its virtual necessity in writing more complicated PHP code?writing functions.

In this month's Script Teez, we're going to take a look at something very important for both its timesaving benefits and its virtual necessity in writing more complicated PHP code. Initially, when writing PHP code, I never bothered to learn how to write my own functions; I would simply do things in a manner that I now classify as the “hard way.” The real test was when I decided to write a replacement for the Perl-based Bugzilla bug-tracking software. I chose to write it in PHP and quickly came to the realization that in order to make the software efficient, I had to make use of custom functions.

Anyone who has written anything in PHP knows what a function is. A function is a block of code that is called from another block of code. The function does a specific task, or function. This can be printing a certain text to the browser, initiating a database connection, or returning a computed value. Functions can take values as input and can return values as output. Most of what you already use in PHP are built-in functions, like print() or sprintf(). The text or arguments you supply between the brackets get passed to the function as input, and what is printed to the screen or returned to a variable is the output.

Creating your own user-defined functions can be very handy. Imagine for a moment that at the top of every page on your site you perform the same action over and over. Let's say you have a piece of code that draws a table on the screen with the title of the page included in it, like a header. There are two ways you can include this in each page. The first is to write the code in a separate file and use the include() function to include it in your page. The second is to write a function to do the same thing.

Using include(), you might have something like this in your index.php file:
<html>
<head>
...
</head>
<?
$text = ``This is my header'';
include(``header.inc.php'');
?>


The included header.inc.php would contain the code you wanted to display at the top of the page. By defining the variable $text beforehand, you can use that variable inside the header.inc.php file. In this case, you would probably use the print() function within the table to display your header.

Another option is to use a function. If you created a function called displayheader(), your index.php file might look like this instead:
<? include(``functions.inc.php''); ?>
<html>
<head>
...
</head>
<? displayheader(``This is my header''); ?>


Here, you use two pieces of PHP code. The first is to include a file called functions.inc.php, which includes your user-defined functions. The second is to call your new function, displayheader(), with the input “This is my header.”

Looking at this, you may not see the obvious benefit, but take a closer look and think about it logically. By including a file using include(), you include the entire file. If you use include() as it was in the first example, the included file can only contain code specific to a single need, in this case, the table that draws the header. As your program grows in complexity, you may find yourself including a number of files in this manner. The disadvantage is that you are calling include() multiple times, and you are scattering many smaller files within your Web directory.

By using a user-defined function, as in the second example, you only need to include one file, in this case, functions.inc.php. As your site grows in complexity, you simply add new functions to this one file. In the end, if you have a dozen functions, you have saved yourself from calling include() a dozen (or more) times, and you reduce clutter by having one file instead of a dozen.

So how do you write a function? It's very simple. Let's take the above example further and see what the contents of functions.inc.php would contain for the function drawheader():

I've slimmed this down quite a bit since we don't need to see how the table itself is constructed, but you get the basic idea. You print the code for the table using the print() function and then you use the print() function to print the value of the $text variable, then continue on to end the table. The function is defined by using the keyword “function” and then the name of the function with any parameters in brackets. For instance, in this example, we define the function called drawheader() and assign the information passed to the function to the variable $text. If you recall, we called drawheader() like this in our previous example:
drawheader(``This is my header'');

By doing this, we are assigning the value “This is my header” to the variable $text, because when we defined the function, we told PHP that any information passed should be stored thus.

You can also assign multiple values to a single function. By calling a function like this:
somefunction(``This is my text'', 1, $var);

and then including in your functions.inc.php something like this:
function somefunction($text, $num, $var) {
 ...
}


you are assigning multiple values to multiple variables. In this instance, when you call somefunction, you pass the variable $text the value of “This is my text”, the variable $num inherits the value “1,” and the variable $var contains the value of what $var contained when the function was called.

Similarly, you can return data from a function. Your function can do anything you want it to, and as we saw above, it prints text directly to the browser. Perhaps you want to write a function that adds two numbers together and returns the sum. You could call the function like this:
$sum = addnums(5,10);

Here, the variable $sum will contain the value returned by the addnums() function. You would then define the function like this:
function addnums($num1, $num2) {
 $result = $num1 + $num2;
 return($result);
}


Here, we see that the function is passed the numbers 5 and 10, they are added together, and the sum, 15, is assigned to $result. Finally, we see that the return command is called to return the value of $result. Because the function returns $result, the variable $sum now contains that value.

Conclusion
As you can see, functions are not necessarily complicated; however, this isn't to say that some functions are not complicated. They are what you make them. But you can also see the advantage of user-defined functions. For very simple Web sites, they may not seem like much of an advantage, but for more complex sites, they are ideal. They save time and they make code reusable. You can use a defined function over and over and obtain different results by passing different values to the function itself. This versatility makes user-defined functions a must for experienced coders and extremely useful for those who are just learning.

About

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

0 comments

Editor's Picks