Created by: Dr.Ferrous
PHP has a lot of built-in functions, also you can create and use your own functions.
Functions helps you to organize the various parts of a script into different tasks that must be accomplished.
To keep some PHP instructions from being executed when the page loads, you can put it into a function.
You can create a function in two ways: with parameters or without parameters.
- The syntax for making a function without parameters is:
The name of your function must begin with either a letter or the underscore, fallowed by any combination of letters, numbers, and the underscore. You cannot use an existing function name (print, echo, isset, and so on).
- The syntax for defining a function with parameters is:
The parameters $param1, $param2, etc. are variables passed into the function. These variables only matter within their function, and they don't interfere with other similar variables outside the function.
Once the function is defined, you can then call and use it as you would any other function in PHP.
A function without parameters can be called using just its name fallowed by round brackets:
- "$arg1", "$arg2", ... are the arguments passed to the function. They are just like variables, and pass values to the function's parameters.
As you can notice, the parameters add more functionality to a function. You can use the second function ( sayHiTo() ) to say "Hi ..." to different names.
A return statement is used to specify a value that a function returns when is called.
You place the return statement as the last line of the function before the closing curly bracket.
The syntax for creating a function that returns values is:
To have a function return multiple values, use the array() function to return an array:
Another aspect on defining your own functions is that you can give the parameter default value in the function's definition.
If a value is passed to a default parameter, the passed value is used; otherwise, the default value is used.
When the value for the second parameter ($y) is not passed, the function uses its default value (5).
A PHP function can be recursive, meaning it can auto-call itself.
A good way to demonstrate the ability of the recursive functions is to solve a factorial equation.
In the fallowing example we have a recursive function that finds the factorial of a number "$nr" (here 9).