30.4. User-Defined Functions

PHP has standard support for user-defined functions. The syntax for defining a function in PHP is as follows:

function <function_name>([<argument1>, <argument2>...]) {
  // code of the function;
  return(<value>);
}

The code for the function is delimited by the braces.

30.4.1. Return Values

The function's return value is determined by the value supplied to the return construct within the user-defined function. Multiple return constructs can be used within the same function; when the function encounters a return construct, the function terminates and returns the appropriate value. A function can return any type of value. The same function can even return several types of values via several return constructs in the same function (although that is generally a bad programming technique).

30.4.2. Arguments

PHP functions support one or more arguments passed to the function. Typically, the number of articles supplied to the function must match the number of arguments defined in the function itself. Supplying more arguments causes the function to simply ignore the extra arguments, but supplying fewer causes an error.

However, sometimes it is useful to define optional arguments—arguments that are replaced by defaults if they are not given when a function is called. For example, suppose you had a function to print a date and need to occasionally specify a particular format for the date but usually want the same format. You could define the function as follows: ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and 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.