It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Understand and use functions in PHP: Part 2

By zooboole

Welcome to the second part of this tutorial on functions. In the previous part we saw a basic PHP User-Defined function and a basic use of it.

In this part we will be diving a bit deeper in how to define a bit complex functions, and in higher use of it. Since functions encapsulate specific tasks, there are many possibilities of using them since we can have many problems to solve in an application.

And like I said previously, one of the main advantages of functions is to help us cut the big problem(entire software) into little ones, which can easily be maintained. Let me illustrate that with a simple example. Assuming we were asked to write a program which displays Good morning in the morning, Good afternoon in the afternoon, and Good evening in the evening. That is the big problem. We can now decide to cut this into little problems(functions) like following.

<?php

// Function to display good morning
function sayGoodMorning()
{
    echo" Good Morning. ";
}

// Function to display good afternoon
function sayGoodAfternoon()
{
    echo" Good Afternoon. ";
}

// Function to display good evening
function sayGoodEvening()
{
    echo" Good Evening. ";
}

Then all we have to do is to detect the current time, and base on it we can call one of these functions and they will display an appropriate greeting like this.

<?php

$currentTime = date('H');

switch($currentTime){

    case $currentTime < 12:
    sayGoodMorning();
    break;

    case $currentTime >= 12 && $currentTime < 17:
    sayGoodAfternoon();
    break;

    default:
    sayGoodEvening();
    break;
}

Here I used one of PHP built-in functions which helps to retreive the current time: date().

Function with parameter

Now let assume we want our program to say the greeting to someone, something like Good morning, John. How do we do that. Simple, we will simply send the name John to the function when we are calling it. And this is how it's done:

<?php

// we keep the name in a variable
$personToGreet = 'John';
sayGoodMorning($personToGreet);

Right now if you do this PHP will yield and error telling you that your function was not declared with the intention to greet people(with the intention to receive a parameter). What that means is we will just add the option to our functions while declaring them like this:

<?php

// Function to display good morning
function sayGoodMorning($to)
{
    echo" Good Morning, $to. ";
}

// Function to display good afternoon
function sayGoodAfternoon($to)
{
    echo" Good Afternoon, $to. ";
}

// Function to display good evening
function sayGoodEvening($to)
{
    echo" Good Evening, $to. ";
}

With this you can call our functions by passing them a variable containing the name of the person to greet. This variable you pass to the function($personToGreet) is called parameter of the function. In this case our functions have each only one parameter, but functions can have as many as possible parameters. Read more about function parameters here.

Formal and Actual parameters

Notice these two variables in our example: $to used while declaring our function, and $personToGreet used when calling the functions.

First the variable $to was not declared before being used inside the function. This is called the function's scope or workspace, some kind of its environment. When you are creating a function you can not predict exactly what information is going to be passed to it. In our case our function can greet anybody, John, Michael, Paul, etc. So to represent those unknown names, we give to the function a variable, $to in our case, to tell it to put whatever name we call it with inside.

Now when we are calling the function, we pass it the real value we want to display, which is in a different variable, $personToGreet in our case. So when the function receives the $personToGreet it will take its value and put it into the variable $to, because in its scope, the function only know the variable $to which is used to say Good morning, $to.

So, these two variables are the same but used in different times in the life time of the program.

The first variable $to, used while declaring the function is like blank placeholder. This variable is called formal.

The second variable $personToGreet is called when we are running the program. This variable is called the actual variable.

Your function's parameters can be of any of these data types: array, callable, boolean, float, int, string, self.

Optional and Default parameters

Now let assume we want our functions to just say the greetings without saying anyone's name. Maybe nobody is around. Ahahaha.

In order to do that we can inform our functions that whenever they are called without any name they should just say the greeting without mentioning anyone. To do that we will make the function's parameter optional like this:

<?php

// Function to display good morning
function sayGoodMorning($to = NULL)
{
    echo" Good Morning, $to. ";
}

//....

With this we can simply call the function like this:

<?php

// With parameter
sayGoodMorning('zooboole');

// Or without parameter
sayGoodMorning();

Here what really happened is not that the function's parameter is really optional. The parameter is there, but we set a default value to it. But because, in this case, the default value is NULL it makes the function feel like nothing is what is passed to it.

So if we change that default value with the name of president Obama, every time we call it without parameter, it's going to greet Obama rather.

<?php

// Function to display good morning
function sayGoodMorning($to = 'Mr Obama')
{
    echo" Good Morning, $to. ";
}

//....

Calling the function without parameter:

<?php

sayGoodMorning(); // will display: Good Morning, Mr Obama.

This can be very useful when you know you function logic can need or not a parameter sometimes.

Functions Returning Values

Now let change the speed a bit. In the example above our functions just echo() some sentence for use. Let now take an example of a function which should calculate the sum of two given numbers.

<?php

function sum($num1, $num2)
{
    $total = $num1 + $num2;
    echo "The sum of $num1 and $num2 is equal to $total";
}

// Then we can call it like this:
sum(11, 4); // The sum of 11 and 4 is equal to 15

But instead of us to display this whole sentence from the function can ask it to give(return) us only the total so that we can decide whatever we want to do with it. In this can we use the keyword return to do that:

<?php

function sum($num1, $num2)
{
    $total = $num1 + $num2;
    return $total;
}

// Then we can call it like this:
sum(11, 4); // 15

Here you can see we have only the total in return. This last option looks more flexible since we can call the function in different contexts with different parameters in order to have a total. It's like the plus sign on a calculator, it give only the total, nothing else. That way you can calculate the sum of any combination of numbers. Let's play with this:

<?php

echo"The sum of 1 and 2 is sum(1,2)";

$firstTotal = sum(1, 2015);

echo"When we add 4 to $firstTotal we will be in sum(4, $firstTotal)";

You can see how that can be useful and flexible.

The value function return can be of any type: String, array, class, object, int, float,etc.

Nesting functions

You probably know HTML. And you also might know that you can do this with HTML:

<h1>
    <em>Emphasize</em>
</h1>

In this snipet, I nested HTML em tag inside the h1 tag. That is also possible with PHP functions.

Although this is not fully supported in PHP yet, it's very useful sometimes....

Let's have a look at how you can do that.

<?php

function parent(){
    echo"Parent function called";

    function child(){
        echo"Child called";
    }

}

print"Calling child first:<br>";
if (function_exists('child')) {
    child();
}else{
    echo"Child can't exist if Parent is not BORN.";
}
print"<hr>";

print"Calling parent after:<br>";
parent();
print"<hr>";

print"Calling child after parent call:<br>";
child();

The inner function exists if we call the first one. This can be cool if you want a function to be available if only some conditions are fullfilled. This is can be really tricky, try calling the child in the parent and vice-versa. Call each one of them inside itself(what is called recursion).

Functional programming

I added this as an information for you to know a bit about it. According to Wikipedia, functional programming is:

functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

In simple words, functional programming is a way(style) of coding in which you create functions that do one thing only. Everything is about functions. No variables to contain a specific data.

This is a very higher level of coding. I might prepare a differet chapter for it. For now if you want to know more about it check the following links:

Conclusion

Well, that was your first step with functions in PHP. You will not necessarily grab everything in one place. Just keep on learning and it will be soon part of you. Functions have more miracles than you can imagine. That is proven with functional programming.

Stay tuned, there more tutorials coming soon with more light on programming. If you have any question, do not hesitate, just comment under this tutorial. Also, don't forget to share this with friends, it helps us.

Last updated 2024-01-11 UTC