PHP Functions

Arrow Functions

$y = 1;

$fn1 = fn($x) => $x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
    return $x + $y;
};
echo $fn1(5);   # => 6
echo $fn2(5);   # => 6

Default parameters

function coffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
# => Making a cup of cappuccino.
echo coffee();
# => Making a cup of .
echo coffee(null);
# => Making a cup of espresso.
echo coffee("espresso");

Recursive functions

function recursion($x)
{
    if ($x < 5) {
        echo "$x";
        recursion($x + 1);
    }
}
recursion(1);  # => 1234

Anonymous functions

$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};
$greet('World'); # => Hello World
$greet('PHP');   # => Hello PHP

Variable functions

function bar($arg = '')
{
    echo "In bar(); arg: '$arg'.\n";
}
$func = 'bar';
$func('test'); # => In bar(); arg: test

Void functions

// Available in PHP 7.1
function voidFunction(): void
{
    echo 'Hello';
    return;
}
voidFunction();  # => Hello

Nullable return types

// Available in PHP 7.1
function nullOrString(int $v) : ?string
{
    return $v % 2 ? "odd" : null;
}
echo nullOrString(3);       # => odd
var\_dump(nullOrString(4));  # => NULL

See: Nullable types

Return types

// Basic return type declaration
function sum($a, $b): float {/\*...\*/}
function get\_item(): string {/\*...\*/}
class C {}
// Returning an object
function getC(): C { return new C; }

Returning values

function square($x)
{
    return $x * $x;
}
echo square(4);  # => 16
Comments