What is a Function in PHP? Definition and Easy Examples

A function is a block of code designed to repeatedly carry out a certain task.

As a result of using functions, we have cleaner, easier to maintain, and more legible code.

Let’s see an example:

(click on the image to open in a new tab)

This is an example of a function converting Celsius degrees to Fahrenheit.

By writing the following function, we can now easily convert different Celsius values to Fahrenheit.

Convert 30 celsius degrees and then 40, 42, 47 to Fahrenheit:

(click on the image to open in a new tab)

We only need to change the $celsius parameter and we get the respective result.

Had we not built a function, we should write the same code again and again.

(click on the image to open in a new tab)

This is repetitive code, a big no no for programming, but also more difficult to read, comprehend and maintain.

Syntax of a PHP Function

The basic syntax for a function is:

(click on the image to open in a new tab)

Here we make use of the function keyword, followed by the name of the function and parenthesis.

Function names can only contain letters, numbers, and underscores. They cannot start with a number, though.

Function names are case-insensitive, so we could also write the above function as Function_Name(), or Function_name(), but it is good practice to call them as we named them in their declaration.

The example code enables the function to execute the code between the curly braces, but does not actually run it.

In order to run the code inside the function, we enter the function’s name followed by parenthesis (call operator).

We refer to this expression as calling the function.

Return a value

In the above example, the Celsius to Fahrenheit converter, we just displayed the result of the functions in the browser for demonstration.

In reality, functions are returning code rather than displaying it.

A return statement forces the function to cease execution.

(click on the image to open in a new tab)

Returning the code enables us storing it to a variable for later use.

Regarding the previous example:

(click on the image to open in a new tab)

The result of the code executed inside the curly braces is now the value of the function itself.

If we want to display this result to the browser, we must echo the function.

(click on the image to open in a new tab)

We can also pass this returned value to another variable and use it as we wish.

(click on the image to open in a new tab)

In a function with the return omitted, the value null will be returned instead.

(click on the image to open in a new tab)

Function Parameters

Inside the parentheses, we can make use of parameters.

(click on the image to open in a new tab)

Function parameters are not mandatory, and there is no limit to how many we can use.

Parameters are a convenient way to create variables that are scoped to the function. They are also convenient regarding naming, since we can give them any name that aligns with the purpose of our program.

Note that, although arguments and parameters are concepts that are used interchangeably, they are not the same.

Parameters are variables passed to a function or method in order to be used by that function when it is called.

Arguments are the values of that variables.

So in the bellow example, $first_name is the parameter and “John” is the argument.

(click on the image to open in a new tab)

Let’s see another example:

(click on the image to open in a new tab)

We see we can call the function multiple times, with different arguments having different results.

By using parameters, we can take a variable from a function scope and give its value to a local scope.

More specifically to our example, breaking down the different scopes:

Function Scope

$greeting and $name are parameters of the function, and they have scope only within the function greet_name. This means they are only accessible and meaningful within the function.

Local Scope

Within each function call (e.g., greet_name(“Hello”, “John”) and greet_name(“Good morning”, “Maria”)), a local scope is created.

In each function call, the values passed as arguments (“Hello” and “John” in the first call, and “Good morning” and “Maria” in the second call) are assigned to the corresponding parameters ($greeting and $name) within the local scope.

We notice that regarding both calls; the parameters are maintaining the integrity of the argument outside that function’s local scope.

Put it simply, when we assign a value to one call, the other is not affected. We can greet both “John” and “Maria” using the same parameter ($name).

For those of you who haven’t met with the concept of scopes yet, let’s dig in a little further.

A few words about Scopes

In programming, scope denotes the area where a function or a variable is accessible to other code.

The concept of scope is fundamental to programming. Each programming language implements it in its own way.

The highest level of scope is global scope.

Here, we both define and output the $pet variable in the global scope. So Cat is displayed in the browser. No problem with that!

Now if a have a function that demonstrates what my pet is, trying to access the global $pet variable from the function’s local scope is going to generate a warning!

(click on the image to open in a new tab)

From a JS programmer perspective, this is very weird, since in JS we can actually do this because of lexical scoping.

PHP behaves differently.

In order to have access to global scope, we need to introduce the global statement and define the variable as global.

(click on the image to open in a new tab)

Now if we echo out the $pet variable outside of the local scope, nothing changes.

(click on the image to open in a new tab)

Changing the global variable inside the local scope, in the above example, will not affect the global variable’s value prior to the function being called.

(click on the image to open in a new tab)

But if we echo it out after the function is called, the pet is now a dog.

(click on the image to open in a new tab)

As we see in the above example, introducing a global variable to a local scope with the global keyword can lead to messiness, and we must constantly be aware of the scope level at which we operate our code.

Another way, the preferred way, since it adheres to the concept of encapsulation, is to pass the global variable as a parameter.

Note that encapsulation is the practice of bundling related data into a structured unit.

So now everything we need “lives” in that function and everything from the outside is coming in as an argument.

That way, everything is clear.

NOTE: In cases where the global variable is a constant, we can access it within the function scope without the use of the global statement or the need to importing it as a parameter, since it has a global scope by default.
(click on the image to open in a new tab)

Passing arguments by reference

When we pass an argument to a function, PHP creates a copy within the function’s scope. Any changes made to the variable inside the function do not affect the original variable outside the function.

(click on the image to open in a new tab)

We have, however, the option to pass an argument by reference using the & symbol in the function definition.

In that case, the function takes a reference to the original variable.

From now on, any modifications made to the variable inside the function will directly affect the original variable outside the function.

(click on the image to open in a new tab)

In this example, the add_two function takes an argument $number by reference.

When the function is called with $another_val as argument, any changes made to $number inside the function directly affect the original value of $another_val outside the function. As a result, the value of $another_val is modified to 12 after the function call.

We must use the option of passing arguments by reference carefully because it can lead to unexpected behavior and loss of transparency in our code.

Passing arguments by value and have functions return the modified value, is more simple and adds predictability to the code.

Default arguments

In PHP, you can set a default argument for a parameter.

This is handy for cases where a specific value is very common and it is repetitive to define it again and again.

(click on the image to open in a new tab)

When you call the hyphenated_word() function and don’t pass the $joiner argument, the function will use the dash () as the default argument:

(click on the image to open in a new tab)

However, if we pass a third argument, the default argument will be ignored.

(click on the image to open in a new tab)

Order of default arguments matters

The parameter list should have default values at the very end.

Creating a function that will have an optional parameter before mandatory parameters would cause an error (Uncaught ArgumentCountError)

(click on the image to open in a new tab)

This is happening because arguments are parsed to function left-to-right.

In our example, we get the error because the first argument (‘short’) we have provided to hyphenated_word2() function gets assigned to the $joiner parameter, overriding the `-` value. This is making $word2 unassigned, that’s why the uncaught argument error.

In the above example, the function definition should be modified like this:

How to use Variadic parameters in PHP

In Programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments

Variadic functions are handy in cases where we do not know all the parameters our function needs at the time of definition.

If you come from a JavaScript background, it is the equivalent of the spread operator.

Let’s see an example:

We create a function and we want to take in as many numbers as we want and add them together.

So we use the splat operator, also known as a three dots operator.

(click on the image to open in a new tab)

So now when calling the function, we can pass in as many numbers as we want.

(click on the image to open in a new tab)

Combining a variadic argument with non-variadic ones is possible provided that the variadic argument is at the end. We can only have one argument with variable length in a function.

(click on the image to open in a new tab)

Type declarations

From PHP 7 onwards, we have the option to declare the type of the parameters we’re going to use in a function, as well as the type of the value that function is going to return.

The advantage of type declarations is code that is more robust and less vulnerable to errors.

For example:

If we want to declare a function that accepts two strings as arguments:

We first need to declare and turn on (value of 1) the strict_types directive, otherwise arguments will be coerced.

(click on the image to open in a new tab)

Had we not declare strict_types=1, the 56.7 float would be coerced to a string and we would get “Hi 56.7”.

In the same way, you can also specify the return type of a function.

For example, have a function that takes as arguments the total points scored by a player and the number of games he played to score these points. The function return average points per game.

We declare the type of the arguments to be integer and the return number to be a string:

(click on the image to open in a new tab)

Suppose that we have a function which doesn’t return a value.

In that case, we use the void declaration.

(click on the image to open in a new tab)

Anonymous Functions

Aside from named functions, PHP allows us to define anonymous functions.

The above function has no name. We also notice that it ends in a semicolon. The semicolon is needed since the function is treated as an expression.

An anonymous function can be stored to a variable.

(click on the image to open in a new tab)

When we var_dump the info of the $divide variable, we see it is actually a closure object:

(click on the image to open in a new tab)

So an anonymous function is a closure object and it can be passed as an argument to another function or be returned from a function.

Being passed as argument(callback) to another function

(click on the image to open in a new tab)

The above multiplier_generator function doesn’t work because PHP has function scope, thus variables inside a function are available only inside that function.

$n is undefined inside the anonymous function.

The use construct comes to the rescue. The ‘use’ construct enables us to inherit variables from the parent scope.

(click on the image to open in a new tab)

We now can call the function which returns an anonymous function that we then store in the $five_times variable.

(click on the image to open in a new tab)

The variable can be invoked as a normal function. It remembers the anonymous function’s return value and reference it in function scope.

Arrow functions

PHP 7.4 introduced arrow functions. Arrow functions are very popular in JS, so for programmers with JavaScript background, this is not a new concept.

The benefits of using arrow functions are cleaner syntax, improved readability and the implication of return statements, which, of course, contribute to the former two.

For example, let’s say we have a very simple function that adds two arguments.

(click on the image to open in a new tab)

We could write it like:

(click on the image to open in a new tab)

We see we do not use the function keyword but the fn keyword instead.

Then we use what’s called a fat arrow. We cannot use curly braces or the return statement.

Arrow functions in PHP cannot perform multi-line expressions.

This is a fundamental difference to Javascript, where using multi-line expressions, with curly braces and the return statement, is an option.

Being strictly one liner, arrow functions in PHP are suitable for small, helper functions or callbacks.

Let’s refactor the capitalized function we used before to use an arrow function.

Here we use the array_map built-in function to apply an anonymous callback function to every element of an array (the array $cities in the example).

(click on the image to open in a new tab)
Note: Unlike JavaScript, we can’t omit the parentheses around a single argument.

Although my blog doesn’t support comments, feel free to reply via email or X.