How to use functions in PHP

Functions are one of the most important concepts in programming.

You can use functions to group together multiple instructions, multiple lines of code, and give them a name.

For example you can make a function that sends an email. For example let’s call it sendEmail, and we define it like this:

function sendEmail() {
  //send an email
}

and you can call it anywhere else by using this syntax:

sendEmail();

You can pass arguments to a function, for example when you send an email you want to send it to someone, so you add the email as the first argument:

sendEmail('test@test.com');

Inside the function definition we get this parameter in this way (we call them parameters inside the function definition, and arguments when we call the function):

function sendEmail($to) {
  echo "send an email to $to";
}

You can send multiple arguments by separating them with commas:

sendEmail('test@test.com', 'subject', 'body of the email');

And we can get those parameters in the order they were defined:

function sendEmail($to, $subject, $body) {
  //...
}

We can optionally set the type of parameters:

function sendEmail(string $to, string $subject, string $body) {
  //...
}

Parameters can have a default value, so if they are omitted we can still have a value for them:

function sendEmail($to, $subject = 'test', $body = 'test') {
  //...
}

sendEmail('test@test.com')

A function can return a value. Only one value can be returned from a function, not more than one. You do that using the return keyword. If omitted, the function returns null.

The returned value is super useful to know the result of the work done in the function, or to use its result after calling it:

function sendEmail($to) {
	return true;
}

$success = sendEmail('test@test.com');

if ($success) {
  echo 'email sent successfully';
} else {
  echo 'error sending the email';
}

We can optionally set the return type of a function using this syntax:

function sendEmail($to): bool {
	return true;
}

When you define a variable inside a function, that variable is local to the function, which means it’s not visible from outside. When the function ends, it just stops existing:

function sendEmail($to) {
	$test = 'a';
}

var_dump($test); //PHP Warning:  Undefined variable $test

Variables defined outside of the function are not accessible inside the function.

This enforces a good programming practice as we can be sure the function does not modify external variables and causes “side effects”.

Instead you return a value from the function, and the outside code that calls the function will take responsibility for updating the outside variable.

Like this:

$character = 'a';

function test() {
  return 'b';
}

$character = test();

You can pass the value of a variable passing it as an argument to the function:

$character = 'a';

function test($c) {
  echo $c;
}

test($character);

But you can’t modify that value from within the function.

It’s passed by value, which means the function receives a copy of it, not the reference to the original variable.

That is still possible using this syntax (notice I used & in the parameter definition):

$character = 'a';

function test(&$c) {
  $c = 'b';
}

test($character);

echo $character; //'b'

The functions we defined so far are named functions.

They have a name.

We also have anonymous functions, which can be useful in a lot of cases.

They don’t have a name, per se, but they are assigned to a variable. To call them, you invoke the variable with parentheses at the end:

$myfunction = function() {
  //do something here
};

$myfunction()

Note that you need a semicolon after the function definition, but then they work like named functions for return values and parameters.

Interestingly, they offer a way to access a variable defined outside the function through use():

$test = 'test';

$myfunction = function() use ($test) {
  echo $test;
  return 'ok';
};

$myfunction()

Another kind of function is an arrow function.

An arrow function is an anonymous function that’s just one expression (one line), and implicitly returns the value of that expression

You define it in this way:

fn (arguments) => expression;

Here’s an example:

$printTest = fn() => 'test';

$printTest(); //'test'

You can pass parameters to an arrow function:

$multiply = fn($a, $b) => $a * $b;

$multiply(2, 4) //8

Note that as the next example shows arrow functions have automatic access to the variables of the enclosing scope, without the need of use().

$a = 2;
$b = 4;

$multiply = fn() => $a * $b;

$multiply()

Arrow functions are super useful when you need to pass a callback function. We’ll see how to use them to perform some array operations later.

So we have in total 3 kinds of functions: named functions, anonymous functions, and arrow functions.

Each of them has its place, and you’ll learn how to use them properly over time, with practice.

Download my free PHP Handbook!