Friday, January 16, 2009

Using PHP Functions to Make Developing Your Website Easier

When developing with PHP you might find you are writing the same code in many places on your website. This repetition of code can make things very time consuming if you ever wanted to make a change to that code. Thanks to PHP functions you can write the code just once for use anywhere in your application.

Writing a PHP function

It's a good idea to have a separate PHP file to hold all your functions, that you include at the top of all your other PHP files. Your functions will need to be included in order for your scripts to be able to use them. Let's look at what makes up a function:

function myfunction() {

echo 'you called my function!';
}

The function declaration is started with function and then the function name -- in this case myfunction. The two brackets have nothing in between them because no parameters need to be passed (see later section). The contents of the function are then inside the curly brackets. The above function simply displays some text to the browser.

Calling a function

To use the above function within your PHP script you can use the following line:

myfunction();

Using parameters

You might need to pass variables to your functions for them to use. These parameter can be put in the brackets after the function name like so:

function myfunction($message) {

echo $message;
}

With the above function you can pass a value for it to use, in this case simply displaying it to the browser:

myfunction('hello world');

Returning values

You can also have your functions return values for you. Your function might do a calculation and you want the result back so you can use it somewhere else in your script. Take the following as an example:

function addnumbers($number1, $number2) {

$result = $number1+$number2;

return $result;
}

This function takes two values, adds them together, and then tells us the result. We can use it like so:

$item1 = 10;
$item2 = 4;
$total = addnumbers($item1, $item2);

The total variable in the above code is now 14

As you can see from the simple examples above, you can use functions to help you manage reusable code in your website easily.

Stefan Ashwell is a PHP developer working for Clear Network, and writes regularly for total-phpTotal PHP, a PHP blog regularly publishing PHP articles and tutorials.

0 Comments:

Post a Comment

<< Home