PHP user-defined functions
Besides the built-in PHP functions, it is possible to create your own functions:- A function is a block of statements that can be used repeatedly in a program.
- A function will not be executed automatically on page load.
- A function will be executed by calling the function.
function functionName() {
code to be executed;
}
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates the beginning of function code, and the closing curly brace ( } ) indicates the end of the function. The function outputs "Hello world!". To call a function, its name must be written followed by parentheses ():
Information can be passed to functions via arguments. An argument is just like a variable. Arguments are specified after the function name, in parentheses. You can add as many arguments as you want, just separate them with commas. The following example defines a function with one argument ($fname). When the familyName() function is called, a name is passed (e.g. Jani) and the name is used in the function, which outputs several different first names but the same last name:
"; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?>
The following example declares a function with two arguments ($fname and $year):
"; } familyName("Hege", "1975"); familyName("Stale", "1978"); familyName("Kai Jim", "1983"); ?>