User-defined functions

2

A function is a sort of subroutine that may accept some values, execute some code, and may return some value back. You can define your own functions:

function plus($a, $b)
{
    return $a + $b;
}

echo plus(10, 20); # Prints 30

A function can have multiple return statements:

function value_or($array, $key, $default)
{
    if(isset($array[$key]))
    {
        return $array[$key];
    }
    else
    {
        return $default;
    }
}

$days_in_month =
[
    'january'  => 31,
    'february' => 28
];

echo value_or($days_in_month, 'january', 'Month not found'); # Prints 31
echo value_or($days_in_month, 'march', 'Month not found'); # Prints "Month not found"

A function can call other functions, including itelf:

function sum_1_to_n($n)
{
    if($n > 1)
    {
        return $n + sum_1_to_n($n - 1);
    }
    else
    {
        return 1;
    }
}

echo sum_1_to_n(10); # Prints "55" which is 1 + 2 + ... + 10

A function doesn't “see” variables outside its scope:

$me = 'Sam';

function hello($name)
{
    echo "Hello $name, my name is $me";
}

hello('Jennifer'); # Prints "Hello Jeniffer, my name is " - function doesn't see $name above

To capture variables from the outer scope you should explicitly use use statement:

$me = 'Sam';

function hello($name) use($me)
{
    echo "Hello $name, my name is $me";
}

hello('Jennifer'); # Prints "Hello Jeniffer, my name is Sam"

You can create an anonymous function and put it into a variable:

$hello = function($name)
{
    echo "Hello $name";
}; # Semicolon

$hello('Jennifer'); # Prints "Hello Jennifer"

Notice that you should put a semicolon after an anonymous function. When you declare an ordinary (named) function — you don't have to do that.

use statement also works with anonymous functions:

$me = 'Sam';

$hello = function($name) use($me)
{
    echo "Hello $name, my name is $me";
};

$hello('Jennifer');  # Prints "Hello Jennifer, my name is Sam"

The purpose of functions is to let you not to repeat yourself. Do not write the same code again to do the same things again — put it in a function instead and call it where you need it.

Rate this post:
Lesson 8
Share this page:

Learning plan

4. Arrays
The very basics of PHP arrays
The things you should know about PHP type system
The basement of PHP control flow structures you should learn before continue
7. User-defined functions
It's time to create your own PHP functions
How reference the same PHP values with different names
Most common and useful PHP built-in functions
The next portion of things you should learn about PHP types