PHP7 declaring scalar types and strongly-typed validation lectures

Source: Internet
Author: User
Tags scalar
PHP7 as early as 2015 has been released, the use of people are more and more, this article we want to talk about PHP7 how to declare scalar type and PHP7 how to do strong type check, do not know the classmate can see Oh!

Scalar type declaration

PHP already has support for class and interface parameter type declarations starting from PHP5.0, PHP5.1 supports array and PHP5.4 support callable. These types of declarations allow PHP to pass in the correct parameters at execution time, allowing the function signature to have more information.

Starting with PHP7, int, float, string, and bool are recognized as type declarations and can be used for function return value types and parameter type declarations

<?phpfunction sum (int $a, int $b): string {return $a + $b;} Var_dump (sum);

Running the above code is OK
The result is string (1) "3", and if the parameter does not conform to the declared type in the weak type check mode, it will be converted according to PHP rules.

PHP7.1 adds a nullable type of declaration and adds void as a function return value type, and a function with a return type of void defined in strongly typed check mode cannot have a return value, even if it returns null:

Declare (Strict_types=1); function Returns_one (): void {return 1;//Fatal error:a void function must not return A Value}fu Nction returns_null (): void {return null;//Fatal error:a void function must not return A value}

Also void applies only to return types, and cannot be used for parameter type declarations, or an error is triggered:

function foobar (void $foo) {//Fatal error:void cannot be used as a parameter type}

Nullable type declaration

Nullable types are primarily used for parameter type declarations and function return value declarations.

The two main forms are as follows:

function Answer (): Int{return null;//ok}function answer ():? Int{return,//Ok}function say (? string $msg) {if ($msg) { echo $msg;}}

From the example is easy to understand, refers to the passage? Indicates that the type of the function parameter or return value is either a specified type or null.

This method can also be used for the definition of an interface function:

Interface Fooable {function foo (? Fooable $f);}

But there is one point to note: If the function itself defines a parameter type and does not have a default value, it cannot be omitted, even if it is nullable, or an error is triggered.

As follows:

Function foo_nullable (? Bar $bar) {}foo_nullable (new bar); feasible foo_nullable (NULL); feasible foo_nullable (); Not feasible

But what if the parameters of the above function are defined as? Bar $bar = null in the form of a third notation is also possible. because = null actually equals? , you can set NULL as the default value for nullable types of parameters.

The declaration for a return type in a class function cannot be overridden by a class, or an error is triggered:

Class Foo{public function bar (): void {}}class Foobar extends Foo{public function bar (): array {//Fatal Error:declarati On Foobar::bar () must is compatible with Foo::bar (): void}}

Strict calibration mode
Strict_types/declare () directive

By default, all PHP files are in weak type check mode. The new declare instruction, by specifying the value of the Strict_types (1 or 0), 1 for the strict type check mode, for function calls and return statements, and 0 for weak type check mode.

DECLARE (Strict_types=1) must be the first statement of a file. If this statement appears elsewhere in the file, a compilation error will occur, and the block pattern is explicitly forbidden.

Similar to the encoding directive, but unlike the Ticks directive, the Strict_types directive only affects files that are specified for use, and does not affect other files that it contains (through include, etc.). This instruction is compiled at run time and cannot be modified. It works by setting a flag bit in opcode that allows the function call and return type check to conform to the type constraint.

<?phpdeclare (Strict_types=1), function sum (int $a, int $b): string {return $a + $b;} Var_dump (sum);

The above code does not conform to the function's return value type declaration, will throw TypeError error

<?phpdeclare (Strict_types=1); function sum (string $a, String $b): string {return $a + $b;} Var_dump (sum);

The above code does not conform to the parameter type declaration of the function, and also throws an error

One exception is that a broad type conversion allows an int to become float, that is, if the parameter is declared as a float type, but it can still accept the int parameter.

<?phpdeclare (Strict_types=1), function sum (int $a, int $b): float {return $a + $b;} Var_dump (sum);

The above code is running normally

In this scenario, we pass an int argument to the function that defines the accept float, and this parameter is converted to float. In addition, the conversion is not allowed.

Related recommendations:

PHP7.2 Version Performance Introduction

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.