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 ...
Get Programming PHP, 3rd Edition 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.