12 Oct 09 PHP Programming Tutorial: More With Functions



Let’s continue from where we left off in our Introduction to Functions tutorial. The basic structure of a PHP function is:

<?php
function function_name(parameter1, parameter2, parameter3, etc.)
{
    function code / statements
}
?>

Functions have three sections: code, parameters, and return values.

The function code is where we write what our function will do. In our earlier example, we wrote three PHP echo statements.

In the parameters, you can pass a variable to your function. This is what gives your functions true flexibility and usefulness. Let’s make a quick example.

<?php
function my_message($message) {
    echo "Listen everyone. I have an important thing to say. Are you ready?<br />";
    echo "Okay then. Here it is: $message";
}
?>

So we have our function with its short two line phrases. Notice the $message variable has not been created but it is mentioned in the parameter. Let’s use it now.

<?php
$message = "Hello world!"; // Now our $message variable exists.
 
echo my_message($message); // Use the my_message function and pass it the $message data we just created.
 
?>

This is our output of the above code:

Listen everyone. I have an important thing to say. Are you ready?
Okay then. Here it is: Hello world!

Here’s another use of this function:

<?php
    echo my_message("I like peanuts!"); // Will use the words inside the quotes.
?>

So now instead of using the $message variable, we’re passing a string. Let’s see our results:

Listen everyone. I have an important thing to say. Are you ready?
Okay then. Here it is: I like peanuts!

Go back to Building PHP Scripts.

Leave a Comment