PHP Functions

A function is a reusable block of code that, given an input, performs some actions and, optionally, returns some result. Applications often perform the same task at different points in the script or in different scripts.

images/articles/php/php-functions.jpg

Functions are designed to allow you to reuse the same code in different locations. A function is a group of PHP statements that perform a specific task. You can use the function wherever you need to perform the task.

1. Function Declaration

Declaring a function means writing it down so it can be used later. A function has a name, takes some arguments, and has a block of code. Optionally, it can define what kind of value is to be returned. You can create a function by putting the code into a function block.

The name of the function has to follow the same rules as variable names, that is, it has to start with a letter or an underscore, and can contain any letters, numbers, or underscore. It cannot be a reserved word.

The general format is as follows:

function function_name()
{
  block of statements;
  return;
}

The return statement at the end of the function stops the function and returns control to the main script. The return is a jump statement that causes the function to end its execution and return to the location where it was called. A function without a return value automatically returns null.

Example

function addNumbers($a, $b) 
{
$sum = $a + $b;
return $sum;
}
$result = addNumbers(2, 3);

The function takes two arguments: $a and $b. The block of code defines a new variable $sum, which is the sum of both arguments, and then returns its content with return. In order to use this function, you just need to call it by its name while sending all the required arguments.

PHP does not support overloaded functions: Overloading refers to the ability of declaring two or more functions with the same name but different arguments. You can declare the arguments without knowing what their types are, so PHP would not be able to decide which function to use.

2. Variable Scope

You are declaring a variable $sum inside the block of code, so once the function ends, the variable will not be accessible any more. That means that the scope of variables declared inside the function is just the function itself. Furthermore, if you had a variable $sum declared outside the function, it would not be affected at all since the function cannot access that variable unless we send it as an argument.

You can create and use a variable inside your function. Such a variable is called local to the function. The variable isn’t available outside of the function. It isn’t available to the main script.

If you want to use the variable outside the function, you have to make the variable global, rather than local, by using a global statement. For example,

global $name;

Similarly, if a variable is created outside the function, you can’t use it inside the function unless it’s global.

3. Function Arguments

A function gets information from outside via arguments. You can define any number of arguments including none. These arguments need at least a name so they can be used inside the function, There cannot be two arguments with the same name. When invoking the function, you need to send the arguments in the same order as declared.

Default Parameters

A function may contain optional arguments, that is, you are not forced to provide a value for those arguments. When declaring the function, you need to provide a default value for those arguments. So, in case the user does not provide a value, the function will use the default one. For this to work as expected, it is important that the parameters with default values are declared to the right of those without default values.

Example

function addNumbers($a, $b, $printResult = false) 
{
$sum = $a + $b;
if ($printResult) {
echo 'The result is ' . $sum;
}
return $sum;
}
$sum1 = addNumbers(1, 2);
$sum1 = addNumbers(3, 4, false);
$sum1 = addNumbers(5, 6, true); // it will print the result

4. Passing Values to Function

You pass values to a function by putting the values between the parentheses when you call the function.

function_name(value, value, ...);

The function must be expecting them. The function statement includes variable names for the values it is expecting.

function function_name($varname1, $varname2, ...)
{
  statements
  return;
}

The function receives the values in the order they are passed. 

Passing the right number of values

A function is designed to expect a certain number of values to be passed to it. If you don’t send enough values, the function sets the missing ones to NULL.

5. Returning Value from Function

PHP will exit the function as soon as it finds the return statement. Still, having multiple return statements can be useful if they are inside conditionals. If you want a function to send a value back to the main script, you can use the return statement.

return value;

For example, the function that adds two numbers:

function add_2_numbers($num1, $num2)
{
  $total = $num1 + $num2;
  return $total;
}

The total of the two numbers is returned. You call the function, as follows:

$sum = add_2_numbers(5,6);

A return statement can return only one value. However, the value returned can be an array, so you can actually return many values from a function.

Additionally, you can omit the return statement if you do not want the function to return anything. In this case, the function will end once it reaches the end of the block of code.

6. Passing Values by Reference

When you pass values into variables in the function definition, you are passing by value. Passing by value is the most common way to pass values to a function. For example,

function add_1($num1)
{
 $num1 = $num1 + 1;
}

When passing by value, copies are made of $num1 and are passed to the function. While $num1 is changed inside the function, by adding 1 to it, the variable $num1 outside of the function is not changed. So, if you call the function with the following statements:

$num1 = 3;
add_1($num1);
echo $num1;

The output is 3.

The $num1 still contains the same value as it did before you called the function. You can change this by making the variable global inside the function or by returning $num1 from the function after it has changed and calling the function, as follows:

$num1 = add_1($num1);

The new value of $num1 is returned from the function and stored in $num1 outside the function.

In some cases, you want to change the values of variables directly, changing their values outside the function. Passing by reference is used for this task. To pass a variable by reference, add & before the variable name, as follows:

function add_1(&$num1)
{
 $num1 = $num1 + 1;
}

When you call this function, a pointer to the location of the variable is passed, rather than a copy of the variable. When you change the variable with statements inside the function, the value at the original location is changed. So, if you call the function with the following statements:

$num1 = 3;
add_1($num1);
echo $num1;

The output is 4.

7. Argument Type Declarations

Early versions of PHP relied exclusively on proper documentation of functions for developers to know what arguments a function accepts. To allow for functions that are more robust, PHP 5 began to introduce argument type declarations, permitting the type of a function parameter to be specified.

  • class name: Argument must be an object or a child of this class (PHP 5.0)
  • interface name: Argument must be an object implementing this interface. (PHP 5.0)
  • array: Argument must be an array. (PHP 5.1)
  • callable: Argument must be callable as a function. (PHP 5.4)
  • bool: Argument must be a Boolean value. (PHP 7.0)
  • float: Argument must be a floating-point number. (PHP 7.0)
  • int: Argument must be an integer. (PHP 7.0)
  • string: Argument must be a string. (PHP 7.0)

A type declaration is set by prefixing the parameter with the type in the function signature. For example,

function myPrint(array $a)
{
foreach ($a as $v) { echo $v; }
}

Failing to satisfy the type hint results in a fatal error. This gives a quick way for the developer to detect when an invalid argument is used.

Type declarations for scalar types - including bool, int, float, and string - were added in PHP 7.