PHP7 scalar type declare usage instance analysis, php7declare
This example describes how to use declare of the PHP 7 scalar type. We will share this with you for your reference. The details are as follows:
To improve execution efficiency, php7 adds declarative features of scalar types (Boolean, floating point, integer, and character) to function methods, saving detection of data types.
Php7 still supports weak type detection, that is, you can still declare the form parameters using the original method.
Scalar Declaration has two features:
Forced mode (default): reflected in type conversion
Strict Mode
Schema Declaration: declare (strict_types = 1 );
The default value is 0. a value of 1 indicates the mode of strict verification.
Available type parameters:
Int-float-bool-string-interfaces-array-callable
Description of the type of the return value. Optional.
Parameters
// Force mode <? Php/*** Created by PhpStorm. * User: bee * Date: * Time: * // function type_weak (... $ int) {return array_sum ($ int);} // in force mode, all real parameters are converted to integer function sum (int... $ ints) {// array_sum () returns the sum of all values in the array as an integer or floating point. Print_r ($ ints); echo "<br>"; return array_sum ($ ints);} echo type_weak (2, '3', 0.11); echo "
Run the following command:
// Declare the mode as a strict mode <? Php/*** Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: * // declare must be in the file header declare (strict_types = 1); // force mode (default) function type_weak (... $ int) {return array_sum ($ int);} // force mode function sum (int... $ ints) {// array_sum () returns the sum of all values in the array as an integer or floating point. Print_r ($ ints); echo "<br>"; return array_sum ($ ints);} echo type_weak (2, '3', 0.11); echo "
Run the following command:
Return Value
<? Php/*** Created by PhpStorm. * User: bee * Date: 2016/4/22 * Time: */declare (strict_types = 0); // force mode (default) function type_weak (... $ int): int {return array_sum ($ int);} // force mode function sum (int... $ ints): int {// array_sum () returns the sum of all values in the array as an integer or floating point. Print_r ($ ints); echo "<br>"; // return array_sum ($ ints) + 0.6;} echo type_weak (2, '3 ', 0.11); echo "
Run the following command: