The methods in PHP are quite useful to be able to encapsulate a specific functionality in one place and be able to reuse that code many times. That is why we are going to see how we can create a method in PHP.
Define the method in PHP
To create a method in PHP we use the reserved word function followed by the name of the method, the parentheses with or without method parameters between the parentheses.
The syntax of a method in PHP would be the following:
function methodName(parameters) {
// Method Code
}
Next we proceed to create a method in PHP that helps us add two integers.
First we put the basic structure of the method:
//Method to add two integers
function add($i,$j){
....
}
Once the basic structure of the method has been defined in PHP we are going to proceed to write the functionality for our method. In this case it is simple, since we will add the two numbers defined as parameters:
$i=intval(trim($i)); //get integer part of $i
$j=intval(trim($j)); //get integer part of $j
return $i+$j;
We see that the result of the method is returned using the return operator.
The PHP to add two numbers it would look like this:
function add($i,$j){
$i=intval(trim($i));
$j=intval(trim($j));
return $i+$j;
}
Execute a method in PHP
Once we have defined our method in PHP we move on to execute it. To execute a method in PHP we will enter the name of the method followed by the values that we assign to the parameters that the method expects.
In our example of the add method we could execute the method in the following ways:
// execution of the php script
echo methodAdd(200,797)."<br>"
echo methodAdd('123','97')."<br>"
echo methodAdd('123.78','97.90')."<br>"
echo methodAdd('b','a')."<br>"
I hope this simple explanation of how to create a method in PHP.
