Function in PHP

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 execute automatically when a page loads.

  • A function will be executed by a call to the function.

Create a Function

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!

⭣ Example ⭣

Call a Function

To call the function, just write its name followed by parentheses ():

⭣ Example ⭣

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.

Function Arguments

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:

⭣ Example ⭣

The following example has a function with two arguments ($fname, $year):

⭣ Example ⭣

Default Argument Value

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:

⭣ Example ⭣

Functions - Returning values

To let a function return a value, use the return statement:

⭣ Example ⭣

Passing Arguments by Reference

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:

⭣ Example ⭣

Use a pass-by-reference argument to update a variable:

Variable Number of Arguments

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.

⭣ Example ⭣

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.

⭣ Example ⭣

The variadic argument must be the last argument:

! Warning !

If the variadic argument is not the last argument, you will get an error.

⭣ Example ⭣

Having the ... operator on the first of two arguments, will raise an error: