2.4. Using Functions

Applications often perform the same task at different points in the script or in different scripts. Functions are designed to allow you to reuse the same code in different locations. A function is a group of PHP statements that perform a specific task. You can use the function wherever you need to perform the task.

For example, suppose you display your company logo frequently throughout your Web site with the following statements:

echo "<p><img src='Images/logo.jpg' width='50' height='50' hspace='10' align='left' /></p>";
echo "<p style='font-size: x-large'>My Fine Company</p>";
echo "<p style='font-style: italic'>quality products</p>";

Rather than typing this code in every place in your scripts where you want to display your logo, you can create a function that contains the statements and name it display_logo. Then, you can just use the function whenever you want to display your logo. Using the function looks like this:

display_logo();

You can see that using this one line saves a lot of typing and is easier to read and understand than typing the echo statements everywhere the logo is needed.

2.4.1. Creating a function

You can create a function by putting the code into a function block. The general format is as follows:

function functionname()
{
   block of statements;
   return;
}

For example, you can create the function display_logo() that we discuss in the preceding section with the following statements:

function display_logo() { echo "<p><img src='Images/logo.jpg' ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.