Latest web development tutorials

PHP scalar type and return value type declaration

PHP 7 New Features PHP 7 New Features


Scalar type declaration

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

PHP 7 increases the characteristic scalar type declared scalar type declaration has two modes:

  • Forced mode (default)
  • Strict Mode

Scalar type declaration syntax:

declare(strict_types=1); 

Strict_types code by specifying a value (1 or 0), 1 strict type checking mode, the role of the function call and return statements; 0 represents weak type checking mode.

Type parameter can be used are:

  • int

  • float

  • bool

  • string

  • interfaces

  • array

  • callable

Examples of enforcement mode

Examples

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

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

The above program execution output is:

9

Examples of summary parameters 4 4.1 converted to an integer and then summed.

Strict Mode Examples

Examples

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

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

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

The above program because of the strict mode, so if you type appears unwell integer parameter being given, execution output is:

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

Return type declaration

PHP 7 adds support for the return type declaration, it indicates the return type of the function return value type declaration.

Can declare the return types are:

  • int

  • float

  • bool

  • string

  • interfaces

  • array

  • callable

Return type declaration examples

Example, asked to return to an integer:

Examples

<? php
declare (strict_types = 1);

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

print (returnIntValue (5));
?>

The above program execution output is:

5

Examples of error return type declaration

Examples

<? php
declare (strict_types = 1);

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

print (returnIntValue (5));
?>

The above program because of the strict mode, the return value must be an int, but the results are float, it will be given, execution output is:

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

PHP 7 New Features PHP 7 New Features