Defining a Function

To define a function, use the following syntax:

function [&] function_name ( [ parameter [, ... ] ] )
{
  statement list
}

The statement list can include HTML. You can declare a PHP function that doesn’t contain any PHP code. For instance, the column( ) function simply gives a convenient short name to HTML code that may be needed many times throughout the page:

<? function column(  ) { ?>
</td><td>
<? } ?>

The function name can be any string that starts with a letter or underscore followed by zero or more letters, underscores, and digits. Function names are case-insensitive; that is, you can call the sin( ) function as sin(1), SIN(1), SiN(1), and so on, because all these names refer to the same function.

Typically, functions return some value. To return a value from a function, use the return statement: put return expr inside your function. When a return statement is encountered during execution, control reverts to the calling statement, and the evaluated results of expr will be returned as the value of the function. Although it can make for messy code, you can actually include multiple return statements in a function if it makes sense (for example, if you have a switch statement to determine which of several values to return).

If you define your function with the optional ampersand before the name, the function returns a reference to the returned data rather than a copy of the data.

Let’s take a look at a simple function. Example 3-1 takes two strings, concatenates ...

Get Programming PHP 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.