Functions
PHP Functions are extremely useful, and they can save you from writing a bunch of redundant code. These are arguably the most powerful component of any language. Functions can separate your code to create a sense of logical flow. You can also add parameters, or arguments, to functions, where you can see that power at the bottom of this page. Functions have a limited scope, which I believe is an asset. This means that if you define a variable inside the function, you cannot reference that variable outside of the function.
Example
function greetings()
{
echo "Greetings";
}
greetings();
Result
Here, we have a function called greetings
. After we define the function, we called the function with greetings();
. Pretty simple, huh? Now, let’s make our functions even more useful by adding arguments.
Function Arguments
Example
function sampleFunction($argument1)
{
echo $argument1;
}
sampleFunction("Something");
Result
Woot woot! We just used a parameter. A parameter is like a variable of the function that is defined when you call the function later. We can see how it is more useful in the next example.
Example
function addingFunction($parameter1, $parameter2)
{
echo $parameter1 + $parameter2;
}
addingFunction(333, 444);
Result
This is similar to the last example. At the end, we call our function addingFunction()
. We pass in two parameters this time: 333 and 444. Where 333 is being passed into the addingFunction
as $parameter1
and 444 is also passed in as $parameter2
. Once they are both passed in, we echo the sum of the two parameters. In the result, you can see that echo sent back 777. The final statement that executed was more like echo 777;
. Nice job!
Like I said, understanding functions is crucial to your success as a programmer.