PHP 7 Declaration of scalar types in parameters and return values

Lecture



Declaration of scalar types ¶

The scalar type declaration is introduced in two versions: coercive (by default) and strict. The following types can be used to declare parameters (in both variants): strings (string), integers ( int ), rational numbers (float) and logical values ​​( bool ). They supplement the arguments of other types introduced in PHP 5: the names of classes, interfaces, array, and callable.

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

var_dump (sumOfInts (2, '3', 4.1));

The result of this example:

 int (9)

To set strict mode, you need to place one declare directive at the very beginning of the file. This means that the severity of the declaration works at the file level and does not affect the rest of the code. This directive affects not only the parameter declaration, but also return values ​​of functions (see return type declaration), built-in PHP functions, and functions of loaded extensions.

For detailed documentation and usage examples, see the type declaration section.

Declaration of Return Values ​​¶

PHP 7 adds support for return type declarations. Similar to the argument type declaration, the return value type declaration indicates what type of value the function should return. For the return type declaration, the same types are available as for the argument type declaration.

<? php

function arraysSum (array ... $ arrays): array
{
return array_map (function (array $ array): int {
return array_sum ($ array);
}, $ arrays);
}

print_r (arraysSum ([1,2,3], [4,5,6], [7,8,9]));

The result of this example:

 Array
 (
     [0] => 6
     [1] => 15
     [2] => 24
 )

For detailed documentation and usage examples, see the return type declaration.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)