Get up to 80 % extra points for free! More info:

Lesson 14 - Declaring custom functions in PHP

In the previous exercise, Solved tasks for PHP lesson 13, we've practiced our knowledge from previous lessons.

In the previous lesson, Solved tasks for PHP lesson 13, we introduced and tried out several PHP string functions. In today's lesson, we're going to show you how to create your own functions.

Creating custom functions

We were using only PHP functions till now, so now we will delve into new territories once again and create our own functions. Decomposing scripts into multiple functions has the following advantages:

  • Clarity - If an algorithm is made up of multiple steps, we create a function for each step and call these functions one by one. Take our e-mail form from previous lessons, it made sure that everything was filled-in and sent an e-mail afterward. Everything was written in the same spot and made things rather confusing. The right way to do that is to call a validation function and then an email sending function. Each function has a specific responsibility. This way, the code is way more readable.
  • DRY - DRY stands for Do not Repeat Yourself, which is one of the best practices in programming and disapproves duplicated code. If we want to use a part of the code more than once, we don't rewrite it, we make it into a function and call it later from multiple places. If we want to correct something in the code, we don't have to correct it everywhere, but only in that single function.
  • Allow us to use libraries - Functions, which we use a lot, can be set up as stand-alone files called libraries. If we create a user-login library, we will be able to use it in multiple projects. We'll just load it and use the functions without having to write them again.

Note: In other courses, we'll show how to gather functions into objects. This way, we'll reach really extensible and high-quality code.

A properly written program should always be made up of several short functions, and should not look like a long noodle of code :)

A simple function

Let's create a simple function that prints out some text. We'll declare the function using the function keyword, followed by the name of the function (in camelCase) and a block of parentheses. The function body will be wrapped in a block of curly-brackets.

A function should be named based on what it does. It should only do one thing. If we need two things to happen in a particular place, we'll make two functions and call one inside the other. Naming functions in imperative tense is a good practice (greet() and not greeting()). Once a function is declared, we will be able to call it by writing its name and a block of parentheses.

Insert the following code anywhere in the PHP sequence:

function greet()
{
    echo('Welcome to my website');
}

greet();

The output:

Your page
localhost

As you may have guessed, we have to declare the function before we call it. PHP parses the source code from the top to bottom, so if we called a function that is declared later on, it wouldn't recognize it.

Functions with parameters

We are able to pass input parameters to functions as well. Let's make an easy example of a function that sums up 2 numbers. In real life, we wouldn't declare a function as simple as this, but it will work fine as an example. We'll declare lots of more interesting functions later. Add the parameters as variables in the parentheses located at the function head. Multiple parameters are separated by commas:

function sum($a, $b)
{
    $sum = $a + $b;
    echo("Sum: $sum");
}

Afterward, we'd be able to call the function like this:

sum(10, 20);

When calling a function, you can also pass variables as parameters:

$a = $_POST['number1'];
$b = 20;
sum($a, $b);

Variables defined outside of functions are not accessible from the inside. Within a function, you can access the variables that came as input parameters or super-global arrays like $_GET and $_POST. There is a workaround, however, by using the global keyword, but don't do that because all it would do is render the function irrelevant (a one-trick-pony of sorts). If there is a restriction set anywhere, it's usually for a good reason and should not be tampered with. Instead, you should look for the right way to do things :) Always pass everything that a function needs through parameters.

A function returning a value

Functions can also return values. In the examples above, all we did was print text. In real applications, we usually don't write functions like those because they aren't universal. What if you didn't want to print the sum, and wanted to use it as a partial result of another calculation. Reasons like these are why, functions usually return their results instead of printing them. This way, we can do whatever we want to with the returned value from wherever we call it. A function can only return a single value and when it does that, it is terminated. Meaning that code beyond the "point of return" will not be executed. We use the return keyword to return values.

If we needed to return two or more values, we would return an array or we create separate functions for each value, depending on the situation.

Let's modify our sum() function so that it returns the result instead of printing it.

function sum($a, $b)
{
    $sum = $a + $b;
    return $sum;
}

Now we call the function like this:

$sum = sum(10, 20);
echo("Sum: $sum <br />");
echo("Doubled sum: " . ($sum * 2));

By having our function return a value, it becomes completely universal and allows us to both print the value or use it for other calculations. The result could be stored in a database, into a file or pretty much anywhere else.

E-mail sending function

Now let's make a function that will actually be of some use to us. With what you know up until now, you should be able to write a function that sends an email. Go back and take a look at the e-mail form code, and based off of that write a function that sends and email, like this:

function sendEmail($address, $subject, $sender, $message)
{
    $header = 'From:' . $sender;
    $header .= "\nMIME-Version: 1.0\n";
    $header .= "Content-Type: text/html; charset=\"utf-8\"\n";
    $success = mb_send_mail($address, $subject, $message, $header);
    return $success;
}

The function prepares the header based on input parameters and passes it to the mb_send_mail() PHP function, which sends the e-mail. The PHP function returns 0/1 based on whether the email has or hasn't been successfully sent. Our function returns the exact same value.

We would then be able to call the function like this:

$success = sendEmail('[email protected]', 'Email test', '[email protected]', 'Message text');
if (!$success)
    echo('E-mail was not sent successfully, check the address and the sender');

You must agree that writing 5 lines, which are now part of the function, everywhere we needed to send an e-mail would be time-consuming and hard to maintain. Now with this function, all we have to do is write a single line. The only drawback is that the function only works in the file where it's declared. Next time, Solved tasks for PHP lesson 14, we'll go over how to use functions from anywhere without having to rewrite them.

In the following exercise, Solved tasks for PHP lesson 14, we're gonna practice our knowledge from previous lessons.


 

Previous article
Solved tasks for PHP lesson 13
All articles in this section
PHP Basic Constructs
Skip article
(not recommended)
Solved tasks for PHP lesson 14
Article has been written for you by David Capka Hartinger
Avatar
User rating:
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities