Get started and transition to PHP7 (2)--Must pass int, string, bool parameter? No problem

Source: Internet
Author: User
Tags scalar

Type hints, type safe

Real-Park Learning video
The original link of the park learning
One of the most compelling new features in PHP 7 is undoubtedly the scalar type hints. We can use scalar type hints in function parameters and return values, and we can also specify how the scalar type is deduced and matched.

Scalar Type Hints

Type hints is not something new, PHP 5.0 introduces the type hints feature for the first time, allowing us to specify that the function's argument is a specific class or interface type. Then, in PHP 5.1, we can specify that the parameter is an array type, in PHP 5.4, we can specify that the parameter is a "callable (callable)" type (for example: function or closure). After several modifications and discussions of the RFC, PHP 7 finally added the scale type to the type hint.

PHP 7 allows us to use the following 4 scalar types in type hints:

Bool:true/false;
Float: Indicates the type of floating-point number;
int: denotes an integer type;
String: Indicates the type of the strings;
Let's look at an example using the above scalar type hints:

<?phpfunction sendHttpResponse(int $statusCode, string $statusText) { }sendHttpResponse(200, "OK");sendHttpResponse("404", "File not found");

For the above two calls, whether or not the Sendhttpresponse type hints is satisfied depends on how we set up the match.

Coercive Type

This is the default method that PHP 7 takes for scalar type hints, which is to try to convert the parameters to the type required by scalar type hints as much as possible. So, in Sendhttpresponse ("404", "File not Found"), "404" is converted to integer 400, allowing the function to execute normally. Of course, convenience always comes at a price, because type conversions can sometimes result in loss of precision. Let's look at some common examples:

<?phpfunctionCoerciveint(int$a) {Echo "a =".  $a;} Coerciveint (1.5); //1coerciveInt ( "100.1"); //100coerciveInt ( "100int"); //100function coercivefloat $a) { echo  "a =".  $a; }coercivefloat (1); //1.0coerciveFloat ( "3.14"); //3.14coerciveFloat ( "3.14PI"); //3.14             

Here, in particular, the bool type, which is similar to our processing logic in C + +, all express the concept of "null", for example: 0, 0.0, NULL, "0", "" (empty string), [] (empty array), $uninitializedVar (uninitialized variable), will be considered false, except for those cases, which are considered true.

Strict Type

If you do not want PHP 7 to perform the above type conversion and require a strict type match, you can manually enable the "strict mode" of PHP 7. In this mode, any type that is not strictly matched will cause the \typeerror exception to be thrown. Strict type can only be used in Web application, that is, if you are writing a library, you cannot open the Strict type in your code.

Enable strict type is simple, in the first line of PHP code, write on declare (Strict_types=1);.

*"PHP start tag and declare (Strict_types=1), there can be no content, namespace must immediately follow the Declare statement. ”
Special Tips *

Let's look at some examples, which can cause \typeerror exceptions:

<?phpDECLARE (strict_types=1);functionStrictint(int$a) {Echo "a =".  $a;} Strictint (1.5); //\typeerrorstrictint ( "100.1"); //\typeerrorstrictint ( "100int"); //\typeerrorfunction strictfloat (float  $a) {echo " a = ".  $a; }strictfloat (1); //\typeerrorstrictfloat ( "3.14"); //\typeerrorstrictfloat ( "3.14PI"); //\typeerror            

Return Type Hints

In PHP 7, in addition to the type hint function parameters, we can also type the return value of the hint function, as follows:

<?phpfunction divisible(int $dividend, int $divider): int { return $dividend / $divider;}divisible(6, 3);divisible(6, 4);

Return type hints the processing of the type, and the rule used by the parameter is the same. By default, coersive type is used, and when strict type is turned on, types that do not meet the contract result in \typeerror exceptions.

Original:
1190000004150197

Get started and transition to PHP7 (2)--Must pass int, string, bool parameter? No problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.