|
In PHP a funciton is basically a hunk of code that you can call on at anytime to execute. You have already used alot of the built-in functions such as echo(). The great thing about a function is that once you write one, you can call it from anywhere so long as the function is declared before you try to use it. Functions can save you from doing a lot of repetative code, plus they are easy to edit or change afterwards. So lets get started with functions.
Basic Function - With Arguments:
<?
// This first line declares our function and any arguaments it may require.
function functionname(argument1, argument2) {
Your php code will go here
}
// To call the function use this
functionname(argument1, argument2);
?>
Basic Function - Without Arguments:
<?
// This first line declares our function.
function functionname() {
Your php code will go here
}
// To call the function use this
functionname();
?>
Example Function:
<?
// This first line declares our function and any arguaments it may require.
function add($number1, $number2) {
// Add our two arguments together and assign the result to $result
$result = $number1 + $number2;
// Print the value of $result to the screen
echo $result;
}
// Here we call our function with our two arguments 2 and 7 which should print 9 to the screen
add(2,7);
?>
I put alot of my functions in a external file and group them all together in one place, so that I can just include the file with the functions in it on each page. This makes things a whole lot easier. Just remember that variables set outside the function are not available inside the function unless you pass them along to the function and vice versa.
|