Home > Article > Backend Development > Summary of new features added in PHP7 (with code)
This article brings you a summary of the newly added features in PHP7 (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Scalar type declaration
a) There are two modes for scalar type declaration: mandatory (default) and strict mode. The following type parameters are now available (either in forced or strict mode): string, int, float, and bool. They extend other types introduced in PHP5: class names, interfaces, arrays and callback types.
<?php // Coercive mode function sumOfInts(int ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1));
The above result will be output: int(9)
To use strict mode, a declare declaration directive must be placed at the top of the file. This means that scalars are strictly declared configurable on a file basis. This directive not only affects the type declaration of the parameters, but also the return value declaration of the function (see return value type declaration, built-in PHP functions and PHP functions loaded in extensions)
2. Return type declaration
a) PHP 7 adds support for return type declaration. Similar to the parameter type declaration, the return type declaration specifies the type of the function's return value. The available types are the same as those available in the parameter 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 output result is:
Array ( [0] => 6 [1] => 15 [2] => 24 )
3.null coalescing operator
a) Due to the large number of When using ternary expressions and isset() at the same time, we add the syntax sugar of null coalescing operator (??). If the variable exists and is not NULL, it returns its own value, otherwise it returns its second operand.
$username = $_GET['user_name']??'nobody';
4. Spaceship operator (combined comparison operator)
a) The spaceship operator is used to compare two expressions. It returns -1, 0 or 1 when $a is less than, equal to or greater than $b respectively. The principle of comparison follows PHP's regular comparison rules.
<?php // 整数 echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // 浮点数 echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // 字符串 echo "a" <=> "a"; // 0 echo "a" <=> "b"; // -1 echo "b" <=> "a"; // 1 ?>
Recommended related articles:
Summary of new syntax features in PHP7.0 and php7.1
New features of PHP: Usage of finally keyword
The above is the detailed content of Summary of new features added in PHP7 (with code). For more information, please follow other related articles on the PHP Chinese website!