Sage-Code Laboratory
index<--

PHP: Functions

A function in any programming language is a relation between one or argument values and the result value. This term comes from mathematics. Usually a function is a named block of code enclosed in curly brackets. There are two kind: internal (predefined) functions and user defined functions.

User Defined Functions

These are functions that you can define in source code specific to your application. You must be creative when you design a function, to give it a proper name. Usually functions perform an action so they must be verbs or combination of words separated by underscore. The name is case insensitive, but usually you write the name with lowercase characters.

Example:

<?php
/* function with two optional parameters */
function add($x, $y = 0, $z = 0) {
    return $x + $y + $z;
}
/* call function 3 times,
 and make a bulet list with the results */
echo "<ul>";
echo "<li>",add($x=1),"</li>";
echo "<li>",add(1,1),"</li>";
echo "<li>",add(1,1,1),"</li>";
echo "</ul>";
?>

Notes:

Output Parameters

Functions can receive formal parameters by reference. This is explicit in PHP using additional prefix "&" in front of parameter name. Value of these parameters can be modified inside the function body. This way you can create functions that return multiple values back into the arguments.

Example:

<?php
/* function with output parameter */
function add(&$x, $y) {
    $x += $y;
}
/* call function and modify $r */
$r = 0; //prepare a result variable
add($r,1); //call function using a variable
echo "$r"; //expect: 1 (parameter is modified)
?>

Conditional Declaration

PHP is a dynamic language, so it can do weird things you do not expect from a regular computer language. You can decide to create a function or not depending on a particular condition. If the function exist you can call it, otherwise you do not.

Example:

<?php
/* control variable */
$makefoo = true;
/* conditional definition */
if ($makefoo) {
    function foo()
    {
        echo "Foo is defined!";
    }
}
/* conditional call foo() */
if ($makefoo) foo();
?>

Functions & Scope

In PHP, variables can be declared global, local or static. The global variables are visible in any PHP code. Local variables are visible in functions. To make global variables visible in function, you must use keyword: "global". This will prevent "shadowing" effect.

Example:

<?php
$a = 1; //global variable
$b = 2; //global variable
function firstTest() {
    global $a, $b;
    return $a + $b;
}
function secondTest() {
    $a = 4; //local (shadow the global $a)
    $b = 4; //local (shadow the global $b)
    return $a + $b;
}
echo firstTest(); // outputs: 3
echo "<br>";
echo secondTest(); // outputs: 8
echo "<br>";
echo "\$a = $a <br>"; // a = 1
echo "\$b = $b <br>"; // b = 2
?>

Note: The global variables are stored into a global dictionary $GLOBAL. You can query a variable by its name using expression: $GLOBAL["name"]. 

Static variables

These variables are local to functions where they are defined. Unlike regular variables these variables are preserving the state when a function is called second time. Variable is not re-initialized second time.

Example:

<?php
function get_next() {
    static $x = 0;
    return ++$x;
}
echo get_next(), PHP_EOL; // outputs: 1
echo get_next(), PHP_EOL; // outputs: 2
echo get_next(), PHP_EOL; // outputs: 3
?>

Local functions

A function can be defined inside another function. This is called "local function" and does not exist outside of the parent function. Unfortunately local functions do not have access to outer variables but can call other local functions and can access global variables.

Example:

<?php
host(); // call before is defined
/* wrapper function */
function host() {
    function bar() //local function
    {
        foo(); //call local function
    }
    function foo() //local function
    {
        echo "I'm foo!";
    }
    bar(); //call local function
}
?>

Recursive Functions

A recursive function is a function that call itself with different parameters. It is very easy to create a wrong program this way that will crash PHP engine. Any recursive function can be replaced by a loop and a stack. So, avoid deep recursive functions as much as possible.

Example:

<?php
/* recursive function */
function factorial($a) {
    if ($a == 0) {
        return 1;
    } 
    else {
        return $a * factorial($a - 1);
    }
}
echo factorial(10),"<br>";
echo factorial(20),"<br>";
?>

Variable arguments

A function can accept a variable list of arguments. All arguments are captured into an array. To declare this array you can use "..." in front of array parameter like in C. Then you can use this array to read all values and use them to produce a result. 

Example:

<?php
/* variable number of arguments */
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}
echo sum(1, 2, 3, 4); //expect 10
?>

Using type hint

PHP is dynamic language, however the code becomes fragile if the type is not enforced. Function parameters can be declared with type. Then if you call the function with the wrong type you get an error. To do that you can use following type hints:

class name The parameter must be an instanceof the given class name or interface name.
self The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods.
array The parameter must be an array.
callable The parameter must be a valid callable.
bool The parameter must be a Boolean value: true or false.
float The parameter must be a floating point number.
int The parameter must be an integer.
string The parameter must be a string.
iterable The parameter must be either an array or an instanceof : Traversable.
object The parameter must be an object.

Example:

This example will fail. It is because the call for sum is using the wrong types!

<?php
//enforce type verification
declare(strict_types=1);
function sum(int $a, int $b) {
    return $a + $b;
}
sum(1.5, 2.5);
?>

Output:

PHP Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in index.php on line 9 and defined in index.php:4 Stack trace: #0 index.php(9): sum(1.5, 2.5) #1 {main} thrown in index.php on line 4

Note: If you do not enforce types, the automatic conversion will convert the wrong types to good types:

<?php
function sum(int $a, int $b) {
    return $a + $b;
}
echo sum(1.5, 2.5); // expect: 3
?>

Return Type

As you can do for parameters, you can declare a result type for functions. If the function do not return the correct type it can trigger an error. The result type is declared after the function parameters using ":", then function block {...}.

Example:

Following example will fail, since the call will force incorrect result type.

<?php
declare(strict_types=1);
function sum($a, $b): int {
    return $a + $b;
}
echo sum(1, 2.5);
?>

Null return

A function that can return null, need a special notation for return type using prefix "?".

Example:

<?php
function get_item(): ?string {
    if (isset($_GET['item'])) {
        return $_GET['item'];
    } else {
        return null;
    }
}
?>

Function Reference

You can store function name into a variable as string. Then you can use this variable to call the function.  Becouse the function is stored by name, you can set the function name using string manipulation and make dynamic code.

Example:

<?php
function foo() {
    echo "In foo()","<br>";
}
function bar()
{
    echo "In bar():","<br>";
}
// variable function call
$func = 'foo';
$func(); // This calls foo()
// variable function call
$func = 'bar';
$func(); // This calls bar()
?>
Caution: Functions are not first class values in PHP, they cannot be passed by their name identifier. Even anonymous functions or functions created via create_function are passed by an object or string reference. At least so far, PHP is not a "functional programming" language.

Internal functions

PHP comes with many functions and constructs. There are also functions that require specific PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. There are many core functions that are included in every version of PHP, such as: string and variable functions.

Learn HTML, CSS and JavaScript to become a web or a front-end developer.


Read next: Arrays