This article mainly introduced the PHP7 scalar type declare usage, combined with the example form analysis PHP7 The type declare the function, the characteristic and the related use skill, needs the friend can refer to the next
The examples in this article describe the PHP7 scalar type declare usage. Share to everyone for your reference, as follows:
PHP7 in order to improve the efficiency of execution, the declaration of scalar type (Boolean, float, integer, character) is added in the function method, which saves the detection of data type.
PHP7 still supports weak type detection, which means that formal parameters can still be declared in the original way.
There are two characteristics of scalar declarations:
Mandatory mode (default): reflected on type conversions
Strict mode
Mode declaration: Declare (Strict_types=1);
The default value is 0, and a value of 1 represents a pattern for strict validation
Types of parameters that can be used:
Int-float-bool-string-interfaces-array-callable
Action on Form participation return value type description, optional
Formal parameters
Forced mode <?php/** * Created by Phpstorm. * User:bee * DATE:2016/4/22 * time:10:17 *///PHP7 before declaring the way function type_weak (... $int) { return array_sum ($int);} Forced mode PHP7 Declaration method//Force mode converts all arguments to integer function sum (int ... $ints) { //array_sum () returns the sum of all values in the array as the result of an integer or floating-point number. Print_r ($ints); echo "<br>"; Return Array_sum ($ints);} Echo type_weak (2, ' 3 ', 0.11); echo "
Run as follows:
Declare the pattern as strict mode <?php/** * Created by Phpstorm. * User:bee * DATE:2016/4/22 * time:10:17 * * *//declare must be in the file header declare (Strict_types=1);//Mandatory mode (default) function Type_weak (...) $int) { return array_sum ($int);} Force mode function sum (int ... $ints) { //array_sum () returns the sum of all the values in the array as the result of an integer or floating-point number. Print_r ($ints); echo "<br>"; Return Array_sum ($ints);} Echo type_weak (2, ' 3 ', 0.11); echo "
Run as follows:
return value
<?php/** * Created by Phpstorm. * User:bee * DATE:2016/4/22 * time:10:17 */declare (strict_types=0);//Mandatory mode (default) function Type_weak (... $int): int{ re Turn array_sum ($int);} Force mode function sum (int ... $ints): int{ //array_sum () returns the sum of all the values in the array as a result of an integer or floating-point number. Print_r ($ints); echo "<br>"; Strict mode error return array_sum ($ints) +0.6;} Echo type_weak (2, ' 3 ', 0.11); echo "
Run as follows: