Easy Tutorial
❮ Php Imagecolorclosest Func Mysqli Change User ❯

PHP Scalar Types and Return Type Declarations

PHP 7 New Features


Scalar Type Declarations

By default, all PHP files are in weak type checking mode.

PHP 7 introduces the feature of scalar type declarations, which come in two modes:

The syntax for scalar type declarations:

declare(strict_types=1);

In the code, by specifying the value of strict_types (1 or 0), 1 indicates strict type checking mode, which applies to function calls and return statements; 0 indicates weak type checking mode.

The available type parameters are:

Coercive Mode Example

Example

<?php
// Coercive mode
function sum(int ...$ints)
{
   return array_sum($ints);
}

print(sum(2, '3', 4.1));
?>

The above program outputs:

9

In this example, the parameter 4.1 is converted to the integer 4 before addition.

Strict Mode Example

Example

<?php
// Strict mode
declare(strict_types=1);

function sum(int ...$ints)
{
   return array_sum($ints);
}

print(sum(2, '3', 4.1));
?>

The above program, due to strict mode, will throw an error if non-integer types are encountered in the parameters, and outputs:

PHP Fatal error:  Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, called in……

Return Type Declarations

PHP 7 adds support for return type declarations, which specify the type of the value returned by a function.

The return types that can be declared are:

Return Type Declaration Example

In this example, the function is required to return an integer:

Example

<?php
declare(strict_types=1);

function returnIntValue(int $value): int
{
   return $value;
}

print(returnIntValue(5));
?>

The above program outputs:

5

Return Type Declaration Error Example

Example

<?php
declare(strict_types=1);

function returnIntValue(int $value): int
{
   return $value + 1.0;
}

print(returnIntValue(5));
?>

The above program, due to strict mode, requires the return value to be an int, but the calculation result is a float, so it will throw an error, and outputs:

Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...

Void Functions

There is also a return type of void, where functions declared as void must not return a value, not even null.

Void functions can omit the return statement or use an empty return statement.

Example

<?php
function swap(&$left, &$right) : void
{
    if ($left === $right) {
        return;
    }

    $tmp = $left;
    $left = $right;
    $right = $tmp;
}

$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

The above example outputs:

null
int(2)
int(1)

PHP 7 New Features

❮ Php Imagecolorclosest Func Mysqli Change User ❯