Learn PHP in One Day and Learn It Well

PHP for Beginners with Hands-on Project. The only book you need to start coding in PHP immediately. By Jamie Chan

Chapter 7: Functions

In this chapter, let’s move on to talk about functions.

We have already encountered functions in previous chapters. For instance, in Chapter 5, we learned to use various PHP functions to work with strings and arrays. In this chapter, we’ll learn to define our own functions.

7.1 Defining our own Functions

To define our own functions, we use the syntax below:

function functionName(list of parameters) {
	//code to be executed;
	//return statements, if any
}

All function declarations must start with the function keyword.

Next, we have the function name. Function names in PHP are not case-sensitive and can contain letters, numbers, or underscores. However, they must start with a letter or an underscore. Similar to variable names, we commonly use camelCase or underscores when naming functions. In this book, we’ll use camelCase.

After the function name, we enclose the list of parameters (if any) that the function needs in a pair of parentheses. Parameters are variables used for storing values that we pass to the function; the values that we pass are known as arguments.

After declaring the function, we use curly braces to enclose the code that we want the function to perform. If the function returns a result, we use the return keyword. Got it?

Let’s look at some examples.

Example 1

function displayGreetings(){
	echo 'Hello';
}

Here, we declare a function called displayGreetings() that has no parameters (as indicated by the pair of empty parentheses after the function name). This function simply echoes the word “Hello”. To call the function, we use its name followed by a pair of parentheses:

displayGreetings();

This gives us

Hello

as the output.

Example 2

function displayGreetings2($name, $message){
	echo "Hello $name, $message";
}

Here, we declare a function called displayGreetings2() that has two parameters – $name and $message .

If we call the function using the following statement

displayGreetings2('Jamie', 'good morning');

the arguments 'Jamie' and 'good morning' will be assigned to the parameters $name and $message respectively. When we run the code above, we’ll get

Hello Jamie, good morning

as the output.

Example 3

We can provide default values for parameter(s) when we declare our functions.

function displayGreetings3($name, $message = 'have a good day'){
	echo "Hello $name, $message";
}

In the example above, we declare 'have a good day' as the default value for the parameter $message (refer to the underlined code). To call the function, we can use the statements below:

displayGreetings3('Jamie');
echo '<BR>';
displayGreetings3('Jamie', 'how are you?');

In the first function call, we omitted the second argument. When we do that, the function uses the default value 'have a good day' as the value for $message .

If we run the code above, we’ll get

Hello Jamie, have a good day
Hello Jamie, how are you?

as the output.

When we declare functions with default values for parameters, note that parameters with default values must come after parameters without default values. If we declare a function as

function redundantDefault($a = 1, $b){
 	//some code
}

the default value for $a will not work as it comes before $b (which does not have a default value); we’ll still need to provide two arguments when calling the function.

Example 4

Last but not least, functions can return a result after they complete their tasks.

function addNumbers($num1, $num2, $num3){
	return $num1 + $num2 + $num3;
	echo 'Hello';
}

The function above returns the sum of $num1$num2 and $num3 using a return statement. Once a return statement is executed, the function exits, and any statement after the return statement is not executed.

We can assign the result returned by the function to a variable or use the echo statement to display the result directly.

If we call the function above using the following statement:

echo addNumbers(9, 6, 1);

we’ll get

16

as the output. The statement

echo 'Hello';

is not executed as it comes after the return statement.

7.2 Type Declaration

The examples in the previous section illustrate the main points we need to know when defining our own functions. Before we move on to the next chapter, I would like to discuss type declaration (also known as type hinting) in this section.

Type declaration is a feature added to newer versions of PHP. This feature is optional but good to implement if you are certain your code will only run on PHP 5 (preferably PHP 7) and above.

First, what is type declaration?

As mentioned previously, PHP is a loosely typed language. In the examples above, when we declared the parameters of our functions, we did not indicate their data types. If the arguments that we pass to the function are of invalid data types, PHP will try its best to execute the function.

For instance, with reference to Example 4 in the previous section, if we try to run the following statement

echo addNumbers('9', '6', '1');

we won’t get any errors.

Although we pass three strings to the addNumbers() function, PHP converts them to integers for us automatically and executes the function. Hence, we’ll get 16 as the output.

Such flexibility makes PHP a very easy language to program in. However, depending on the requirements of the site you are building, you may not want the function to run when the data type is incorrect. In cases like that, you can use type declaration.

Type declaration allows us to state the data types of a function’s parameters when we declare it.

This feature is available from PHP 5 onwards. However, in PHP 5, type declaration does not work for scalar data types. Scalar data types refer to data types that store a single value, such as intfloatbool and string . Type declaration only works for data types like arrays.

To use type declaration with scalar data types, we need PHP 7 and above. In addition, we need to add a strict_types declaration to our script and set strict_types to 1 .

To illustrate how this works, let’s look at an example. This example works in PHP 7.

Create a new file in Brackets and name it typedec.php. Add the following code to it.

<?php
	declare(strict_types=1);
		
	function addNumbersStrict(int $num1, int $num2, int $num3){
		return $num1 + $num2 + $num3;
	}
	echo addNumbersStrict('9', '6', '1');

Here, we set strict_types to 1 using a built-in function called declare() . This statement must be the first statement in our script.

Next, we declare a function called addNumbersStrict() with three parameters $num1$num2 and $num3 . We indicate that these parameters must be of int type by adding int in front of their names. Finally, we call the function by passing '9''6' and '1' to it.

If you run the code above, you’ll get an output similar to what is shown below:

Fatal error: Uncaught TypeError: Argument 1 passed to addNumbersStrict() must be of the type int, string given...

Next, change the echo statement to

echo addNumbersStrict(9

and rerun the code. As 96 and 1 are of int type, we won’t get any errors now. Instead, we’ll get 16 as the output. Got it?

Besides doing type declaration for parameters, we can do it for the return type if we are using PHP 7 and above. To do that, we indicate the return type using a colon after the parentheses in the function declaration.

Add the following code to typedec.php:

function addTwoNums($a, $b): int {
    return $a + $b;
}
echo '<BR>'.addTwoNums(3, 1);

Here, we indicate that the return value of addTwoNums() should be of int type. Next, we call the function using 3 and 1 as the arguments.

If you run the code above, you’ll get 4 as the output. Next, change the last line to

echo '<BR>'.addTwoNums(3.9, 1);

and run the page again. You’ll get the following output:

Fatal error: Uncaught TypeError: Return value of addTwoNums() must be of the type int, float returned...

This is because 3.9 + 1 gives us 4.9, which is not of int type.