Home > Article > Backend Development > Detailed explanation of the usage of scalar type declare in PHP7
This article mainly introduces the usage of PHP7 scalar typedeclare, and analyzes the functions, characteristics and related usage skills of the scalar type declare in PHP7 in combination with examples. Friends in need can refer to the following
The example in this article describes the usage of PHP7 scalar type declare. Share it with everyone for your reference, the details are as follows:
In order to improve execution efficiency, php7 has added the declaration feature of scalar types (Boolean, floating point, integer, character) in the function method, saving Detection of data type.
php7 still supports weak type detection, that is, formal parameters can still be declared in the original way.
Scalar declaration has two characteristics:
Forced mode (default): reflected in type conversion
Strict mode
Mode declaration: declare(strict_types=1);
The default value is 0, and the value 1 represents a strict verification mode
Usable type parameters:
int-float-bool-string-interfaces-array-callable
Acts on formal participation return value type description, optional
Formal parameters
//强制模式 <?php /** * Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: 10:17 */ // php7之前申明方式 function type_weak(... $int){ return array_sum($int); } // 强制模式 php7声明方式 //强制模式下会将所有实参转换为整型 function sum(int ... $ints) { //array_sum() 将数组中的所有值的和以整数或浮点数的结果返回。 print_r($ints); echo "<br>"; return array_sum($ints); } echo type_weak(2, '3',0.11); echo "<hr>"; echo sum(2, '3',0.11);
The running effect diagram is as follows:
//将模式申明为严格模式 <?php /** * Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: 10:17 */ //declare 必须在文件首部 declare(strict_types=1); // 强制模式(默认) function type_weak(... $int){ return array_sum($int); } // 强制模式 function sum(int ... $ints) { //array_sum() 将数组中的所有值的和以整数或浮点数的结果返回。 print_r($ints); echo "<br>"; return array_sum($ints); } echo type_weak(2, '3',0.11); echo "<hr>"; //实参存在字符串与浮点型,报错 echo sum(2, '3',0.11);
The running effect diagram is as follows:
Return value
<?php /** * Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: 10:17 */ declare(strict_types=0); // 强制模式(默认) function type_weak(... $int) :int{ return array_sum($int); } // 强制模式 function sum(int ... $ints) :int { //array_sum() 将数组中的所有值的和以整数或浮点数的结果返回。 print_r($ints); echo "<br>"; //严格模式下报错 return array_sum($ints)+0.6; } echo type_weak(2, '3',0.11); echo "<hr>"; echo sum(2, '3',0.11);
The operation effect diagram is as follows:
The above is the detailed content of Detailed explanation of the usage of scalar type declare in PHP7. For more information, please follow other related articles on the PHP Chinese website!