(click anywhere to close)
OPEN MENU

[PHP] Functions

category: Website | course: PHP | difficulty:

Before we can start talking about the God of all data types (Objects), I want to talk about functions and variable scope first. Not only are they insanely useful to learn and use early on, they also play a large role in understanding Objects.

We’ve already seen many of PHP’s built-in functions (although there are many more to come), and this chapter will explain how you can create your own such functions.

A function is a block of statements that can be used repeatedly by calling it

Hmm, repeating a set of statements – what’s the difference with a loop? The difference is huge. A function can be defined anywhere within the program, but the code inside will only be executed once you call it. Furthermore, you can call the function from anywhere, anytime you want, whilst loops are rooted to the spot and can’t be called.

Creating a Function

To define your own function, use the function keyword (ain’t programming straightforward, eh?):

function some_function_name() { code }

Naming your own functions follows the same rules as naming variables. Just as built-in PHP functions, the name is case-insensitive.

Then, to call the function from anywhere, simply use the syntax you’re already used to:

some_function_name();

Yes, even when a function takes no parameters, you still need to use the parentheses to tell PHP we’re looking for a function with that name. We’ll look at functions with parameters next.

function print_welcome() {
	echo "Welcome everybody!";
}

print_welcome();

Parameters & Arguments

Like we saw with the built-in ones, functions work at their best when they take a few parameters. You already know how to pass arguments to the function, namely with

some_function_name(arg1, , argn);

But, how do we program the function to be able to accept these arguments and do something with them? For that we use the following syntax:

function some_function_name($par1, , $parn) { code }

Remember that when calling the function we pass in actual values (arguments), while in the function definition we only define variable names (parameters) to hold those values.

//Here we define the function and its parameters
function print_welcome($name, $time) {
	echo "Welcome $name on this lovely $time.";
}

//Here we can pass in the arguments for every parameter
print_welcome("Juan", "afternoon"); //Prints: Welcome Juan on this lovely afternoon.
print_welcome("Batman", "night");   //Prints: Welcome Batman on this lovely night.

Defaults

Times will come when you have a crucial function that can’t be allowed to fail. In those cases, you can supply a default value for parameters. If no argument is passed in when the function is called, the function will use the defined default value instead. The syntax is what you’d expect:

function some_function_name($par1 = default_value) { code }
function print_welcome($name, $time = "day") {
	echo "Welcome $name on this lovely $time.";
}

print_welcome("Juan", "afternoon"); //Prints: Welcome Juan on this lovely afternoon.
print_welcome("Batman");	//Prints: Welcome Batman on this lovely day.

The return Statement

All these functions are nice, but you might struggle to find a use for them. Well, remember that nearly all built-in PHP functions returned something? For example, the in_array() function returned a value true (if the element was in the specified array) or false (if not).

We can do that with our own functions as well. In fact, it’s so important, that it has become a language construct again. The syntax for returning something is

return value;

When a return statement is executed, the function returns the value after it, and immediately stops executing the rest of the function. This can be useful, because you don’t want to waste resources on executing other code (or even returning other values) when you’ve already found your value.

function find_highest($x, $y, $z) {
	$current_highest = $x;
	if($y > $current_highest) {
		$current_highest = $y;
	}
	if($z > $current_highest) {
		$current_highest = $z;
	}
	return $current_highest;
}

$max_number = find_highest(4,10,-2);    //$max_number is 10
$max_number = find_highest(0, 0, 1000); //$max_number is 1000

Variable Functions

There’s an alternative syntax for creating functions. Instead of defining a function separately from the rest of the code, you can put a function inside a variable. The variable is then said to be callable, and the syntax is:

$some_function_name = function () { code };

Its functionality is identical to the other syntax, and the other syntax is usually regarded as more easily readable and maintainable. Then why would I want to do this? Because this way, you can change functions on the fly! You can assign a different function to the same variable name any time you want, and from that moment on every call made to that variable will use the new function.

The dollar sign is part of the function name, don’t forget to include it.

$greeting = function() {
	echo "Welcome everybody!";
};

$greeting(); //Prints: Welcome everybody!


$greeting = function() {
	echo "Goodbye my friends!";
};

$greeting(); //Prints: Goodbye my friends!

Return Types & Type Hinting

Because functions usually contain important functionality, it’s common to check whether the parameters are of the right data type, and whether the returned value is of the right data type. It would be a pain to have to write lots of if-statements to check those data types, which is why PHP has return types and type hinting.

To tell PHP that a function should return a value of a certain data type, use:

function some_function() : type { code };

If the returned value is not of that type, PHP throws an error and quits. If your function shouldn’t return anything, use return type void.

//Signing in the user should return true if succeeded, false if not (thus, a boolean value)
function sign_in_user() : bool {
    //This line will be explained next chapter
    global $username_correct, $password_correct;
    
	if($username_correct && $password_correct) {
		return true;
	} else {
		return "SOMETHING WENT WRONG";
	}
}

$username_correct = true;
$password_correct = true;
$login = sign_in_user(); //$login is true

$username_correct = true;
$password_correct = false;
$login = sign_in_user(); //PHP throws an error and quits executing, because we returned a string.

To tell PHP that certain parameters should be of certain data types, use

function some_function(type $par1, …, type $parn) { code };

Again, if these conditions are not met, PHP throws an error and kills a kitten. As you can see, using these return types and type hinting is completely optional – functions would work just fine without them – but it’s generally recommended to use them, as it makes your code clearer and less error prone.

function find_highest(int $x, int $y, int $z) {
	$current_highest = $x;
	if($y > $current_highest) {
		$current_highest = $y;
	}
	if($z > $current_highest) {
		$current_highest = $z;
	}
	return $current_highest;
}

$max_number = find_highest(4,10,-2);    //$max_number is 10
$max_number = find_highest(0, "two and a half", 1000); //ERROR
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)