PHP Tutorial: The function of functions

Functions in PHP, are wonderful tools. They allow you to go with the DRY (don’t repeat yourself) style of writing code.
Functions are good for when you want to run some code often, perhaps a small block. We’ll make a function called “tax()”, you create a function like this:

/* our function will have two parameters:
$amount which will be put in by you when you call the function, and
$rate which, by default, will be 0.05, but you can change it anytime */
function tax( $amount, $rate = 0.05 ) {
/* now we need to find out how much the tax will be
 $amount is set when the function is called */
$tax = $rate*$amount;
/* now return the value, for use in your script */
return $tax;
/* now you simply call the function: 
the following code will echo:  5 */
echo tax(100);
/* adding a new tax rate 
the following code will echo 8 */
echo tax(100,0.08);

Variables outside a function cannot be used inside a function except for three cases: (to my knowledge)

Using a variable inside a function by definition of global ;

$fruit = 'Apple';
function fruit() {
    global $fruit;
    echo $fruit;
/* However */
function rotten() {
    echo "Rotten $fruit";
/* This will only produce the word Rotten, not Rotten Apple. 
in fact you will get an error! something like this: 
Notice: Undefined variable: fruit in yourfilename.php on line 16 */

So that’s the basics of functions, I hope that helps!

Author: Mike on March 25, 2011
Category: PHP, Tutorials
Tags: , , ,

One thought on “PHP Tutorial: The function of functions”

  1. Suzy says:

    You saved me a lot of hassle just now.

Comments are closed.

Last articles