PHP is provided various built-in functions to the user. You can also create user-defined functions too.
A PHP function is a block of statements that can be reused many times. It can take input as an argument list and return value.
PHP function will be only executed by calling the function.
There are two types of function.
PHP provides various built-in functions. Every PHP built-in function performs some specific task. Let us see it with the help of an example.
PHP user-defined function starts with the
function keyword followed by function name and arguments.
A function can not run until it is called.Please keep in mind that a function is called by its name followed by
A user-defined function can call as follows:
PHP function containing single argument:
PHP function containing multiple arguments:
There are two ways to pass arguments to a function. An argument can be passed to a function using call by value and by reference. By default function argument is passed by value.
Passing argument to a function by reference, allows us to modify function arguments. That is the main reason behind the passing argument by reference.
Passing an argument by reference can be done by prepending ampersand (&) to the argument name in the function definition.
Let us understand the above mention concept using an example.
Therefore, it is clear that a variable value can be changed inside the function when it passes inside the function by reference. Just prepend an & sign to the argument name in the function definition.
The default value for a function's argument can be provided by using assignment operator (
=) in the function definition. If the calling function, does not provide the value then the function will be used as the default value of the argument.
Let us understand with the help of an example.
A function return statement is used to return the value to the calling function. Whenever PHP parser parses the return statement inside the function then it returns the function's value to the calling function and stops the execution of the function.
It is possible to assign function names as strings to variables and then treat these variables exactly as the function name itself.