PHP - Function

php

How can we define a function?

function sum($x, $y) {
    $z = $x + $y;
    return $z;
}

How can we provide default values for function parameters?

function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

How can we pass by reference?

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:

function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}

What are the restriction on the default value?

  1. The default value must be a constant expression, not (for example) a variable, a class member or a function call.
  2. When using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

A function may define C++-style default values for scalar arguments as follows:

function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}

Incorrect usage of default function arguments:

function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour.\n";
}

Can a parameter that is passed by reference have a default value?

Yes. As of PHP 5, arguments that are passed by reference may have a default value.

How can we do "type declaration" with PHP?

Type declarations were also known as type hints in PHP 5. Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

Type Description Minimum PHP version
Class/interface name The parameter must be an instanceof the given class or interface name. PHP 5.0.0
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. PHP 5.0.0
array The parameter must be an array. PHP 5.1.0
callable The parameter must be a valid callable. PHP 5.4.0
bool The parameter must be a boolean value. PHP 7.0.0
float The parameter must be a floating point number. PHP 7.0.0
int The parameter must be an integer. PHP 7.0.0
string The parameter must be a string. PHP 7.0.0

Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool.

What is strict typing?

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.

It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration.

To enable strict mode, the declare statement is used with the strict_types declaration. Enabling strict mode will also affect return type declarations.

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.

To enable strict typing for a file:

declare(strict_types=1);

How can we dump the value of a variable for debugging?

Use the var_dump function:

var_dump($a);

How can we implement variable-length argument lists?

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

In PHP 5.6 and later, argument lists may include the … token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);

You can also use … when calling functions to unpack an array or Traversable variable or literal into the argument list:

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

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);

You may specify normal positional arguments before the ... token. In this case, only the trailing arguments that don't match a positional argument will be added to the array generated by ....

It is also possible to add a type hint before the ... token. If this is present, then all arguments captured by ... must be objects of the hinted class.

function total_intervals($unit, DateInterval ...$intervals) {
    $time = 0;
    foreach ($intervals as $interval) {
        $time += $interval->$unit;
    }
    return $time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';

// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);

For older PHP version, no special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().

function sum() {
    $acc = 0;
    foreach (func_get_args() as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License