PHP Functions
There are two types, they are:
- PHP Built-in Functions
- PHP User-Defined Functions
PHP Built-in Functions
A function is a self-contained block of code that performs a specific task.
It has a huge collection of internal or built-in functions that you can call directly within your scripts to perform a specific task,
like gettype(), print_r(), var_dump, etc.
PHP User-Defined Functions
In addition to the built-in functions, it also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately from the main program.
Creating and Invoking Functions
The basic syntax of creating a custom function can be given with:
Functions with Parameters
You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
You can define as many parameters as you like. However, for each parameter, you specify, a corresponding argument needs to be passed to the function when it is called.
The getSum() function in the following example takes two integer values as arguments, simply add them together and then display the result in the browser.
Functions with Optional Parameters and Default Values
You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by a default value, like this.
Returning Values from a Function
A function can return a value back to the script that called the function using the return statement. The value may be of any type, including arrays and objects.
If you liked our content PHP Functions, then you may also like PHP Functions in Sorting Arrays
Leave a Reply