Functions

If programs are large or you must copy-paste the same code several times within the same file the best way is to use functions.

Defining a function is really simple , there is the keyword function , the function name (your choice) , follow it with ( ),
and specify the instructions it contains . The () can contain a list of parameters (optional).

A function returns a result to the calling code by using the "return: keyword, like this:

return $result;

Example:

function addition($val1, $val2)
{
$sum = $val1 + $val2;
return $sum;
}

Function names are case sensitive, meaning that addition() is not the same as AddiTion().

The instructions contained within a function are not processed (executed) until the function is called, regardless or where within your program the function is defined. This means that theoretically, your functions could be defined anywhere within the program.
Best practice, however, is to define all your functions at the beginning of your program script.

A function is called by its name followed by a set of parentheses, like this:

$var1=4;

$var2=5;

$sum=addition($var1,$var2);

After the function is executed $sum=9;

It is important to note that if you define a variable within a function, that variable is only available within that function; it cannot be referenced in another function or in the main body of your program code. This is known as a variable's scope. The scope of a variable defined within a function is confined to that function -- in other words, it's local to that function.

If a function needs to use a variable that is defined in the main body of the program, it must reference it using the "global keyword, like this:

function addition($val1, $val2)

{

global sum;

$sum = $val1 + $val2;

}

$var1=4;

$var2=5;

$sum=0;

addition($var1,$var2);

echo $sum

While the scope of a variable defined in a function is local to that function, a variable defined in the main body of code has a global scope. The "global" keyword tells PHP to look for a variable that has been defined outside the function.

That is because a variable defined within a function exists only while that function is being processed; when the function ends, the variable ceases to exist.

admin – Thu, 2005 – 07 – 07 11:33