PHP 101 (part 5) - The Wonderland Factor - Calling Godzilla (
Page 4 of 7 )
Next up, user-defined functions.
Most programming
languages provide a number of functions that make coding easier - in PHP 101, we
frequently use the echo() function, and in the last issue, we used a bunch of
database-related functions. But sometimes, it's just more convenient to roll
your own - and so, PHP also allows you to define your own custom functions,
which you can program in accordance with your heart's darkest desires.
In
PHP, a user-defined function is simply a set of program statements which perform
a specific task, and which can be called, or executed, from anywhere in your PHP
script.
There are two important reasons why separating your code into
functions is a "good thing". First, this allows you to isolate your code into
easily identifiable subsections, thereby making it easier to understand and
debug. And second, a function makes your program modular by allowing you to
write a piece of code once and then re-use it multiple times within the same
program.
Here what a function definition looks like:
<?
function godzilla()
{
statement 1;
statement 2;
statement 3;
...
...
}
?>
And once it's defined, you can execute the statements within
the function simply by calling it - like this:
<?
function godzilla()
{
statement 1;
statement 2;
statement 3;
...
...
}
godzilla();
?>
When the PHP parser encounter a function call such as the one
above, control of the program shifts to the location where the function has been
defined. Once the statements in the function block have been executed, control
shifts back to the location where the function was invoked.