PDA

View Full Version : Newbie question..what is a function??


nickbarresi
01-15-2003, 02:37 AM
I'm in the process of learning PHP, and I can't seem to get a grasp on 'functions'.
Consider the following example:

function compute_area($height, $width)
{
return $height * $width;

}

I don't understand this at all, why not just make
$area=$height * $width
???

What exactly is the point of using functions? Maybe someone has a better example...I really appreciate the help

Kiwi
01-15-2003, 10:09 AM
A function is a block of code that can be defined once and invoked from other parts of the program.

The there are a lot of different reasons for writing them: Functions mean that you code is modular -- making it easier to expand and modify the code.
Functions can eleminate errors -- if you have a block of code that is being re-used, then you have to seperately debug each time you have entered it. If you call that code in a function, then you have to debug it once.
Functions make your code more readible -- if you name your functions and variables sensibly, then your code makes more sense.
Functions encourage more robust code -- you can (and should) built error checking into your functions, meaning that the function can be used widely and your application won't crash if you pass a bad variable to the function.
And, an example:
function js_alert($msg) {
// creates a js alert of the string message
if ($msg=="") return; // don't create an empty alert
echo ("\n<script language='JavaScript'><!--\n".
" alert('$msg');\n".
"--></script>");
}This function creates a javascript alert of $msg whenever it's invoked from your php code. It would be useful if you wanted to use a javascript alert, that depended on something that was happening in your php code.