Besides the built-in PHP functions, it is possible to create your own functions.
A user-defined function declaration starts with the keyword
function
, followed by the name of the function:
Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.
Tip: Give the function a name that reflects what the function does!
To call the function, just write its name followed by parentheses
()
:
In our example, we create a function named myMessage()
.
The opening curly brace {
indicates the beginning of
the function code, and the closing curly brace
}
indicates the end of the function.
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument
($fname)
. When the familyName()
function
is called,
we also pass along a name, e.g. ("Jani")
, and the name
is used inside the function, which outputs several different first
names, but an equal last name:
The following example has a function with two arguments
($fname, $year)
:
The following example shows how to use a default parameter. If we
call the function setHeight()
without arguments it
takes the default value as argument:
To let a function return a value, use the
return
statement:
In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function
and the variable that was passed into the function cannot be changed.
When a function argument is passed by reference, changes to the argument also change the variable that was passed in.
To turn a function argument into a reference, the
&
operator is used:
Use a pass-by-reference argument to update a variable:
By using the ...
operator in front of the function
parameter, the function accepts an unknown number of arguments. This
is also called a variadic function.
The variadic function argument becomes an array.
A function that do not know how many arguments it will get:
You can only have one argument with variable length, and it has to be the last argument.
The variadic argument must be the last argument:
If the variadic argument is not the last argument, you will get an error.
Having the ... operator on the first of two arguments, will raise an error: