O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

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

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. By convention, built-in PHP functions are called with all lowercase.

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. You can include any number of return statements in a function (for example, if you have a switch statement to determine which of several values to return).

Let’s take a look at a simple function. Example 3-1 takes two strings, concatenates them, and then returns the result (in this case, we’ve created a slightly slower equivalent to the concatenation operator, but bear with us for the sake of ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required