What are php Functions? Why do we have to use it? How do we use it?
Functions are a very necessary component of php as a matter of fact not just php every programming language. They are amazing, time saving, efficient, fast and gorgeous (heh a bit cheesy? maybe.) Using functions within your code also tends to impress others if you are using the correct syntax for the function and write clean code.
I’ve made a diagram of how a function works so here it is, click on the image to enlarge it.
Also here is a little code for those who are unable to view the image:
-
-
function MyFunction($param1, $param2)
-
{
-
//this is the body of the function
-
//this makes it so if we pass Jon Doe as the paramters it will make it Mr. Jon Doe
-
$name = "Mr. " . $param1 . " " . $param2; //print out the name
-
-
echo $name;
-
-
//Return statement
-
return true;
-
} //end the function
Lets talk about how it works. A function is basically like a food making machine. You give the machine the ingredients and it will make something using the ingredients and produce a new product. Functions work the same way. Function parameters are optional just like regular machines. The parameters are the variable you pass to the function when your calling it. For example If I had a function that would two numbers for me I would use it like this: Add(<num1>,<num2) the num1 and num2 are the parameters and here is an example: add(2,4) and it would return 6.
Let’s see a function at work!
-
-
function Multiply($num1,$num2) {
-
//a function that multiplies 2 given numbers.
-
//make a variable to contain the total/result.
-
$result = ($num1 * $num2);
-
-
//We performed a basic mathematic operation above by multiplying the two numbers.
-
-
//return the value
-
return $result;
-
-
//notice we didn’t do echo $result. We could but if we keep it return we could manipulate the data more.
-
} //end the function
-
-
//Here I’ll have my php codes
-
//We make 2 variables and give them random numbers from 1 to 100.
-
-
//now we can call our function whenever we want. echo "Now Multiplying {$var1} times {$var2} = ";
-
-
//If we put echo $result in the function then we could do echo multiple($var1,$var2) because it is already printing it once.
-
-
//Multiply($var1,$var2) will not print anything, it will simply take 2 numbers multiply them then RETURN the value.
And it should print something like this:
-> Now Multiplying 2 times 19 = 38
-> Now Multiplying 46 times 34 = 1564
Instead of having to write many lines of codes we can use a function to shorten our code and run it more efficiently. You can use php functions for more then just mathematic operations, Every website with php uses Functions. Believe it or not, at least the ones that are stable. As you learn more of how PHP functions work you will begin to understand why you need them and how they help you.
0 Responses to “Php Functions - The Basics.”