Summary of new features in PHP 7.1, and summary of new features in PHP

Source: Internet
Author: User

Summary of new features in PHP 7.1, and summary of new features in PHP

1. null type

The void type is mainly used for parameter type declaration and function return value declaration.

The two main forms are as follows:

<?phpfunction answer(): ?int { return null; //ok}function answer(): ?int { return 42; // ok}function say(?string $msg) { if ($msg) { echo $msg; }}

It is easy to understand from the example, that is, through? Indicates that the type of the function parameter or return value is either the specified type or null.

This method can also be used to define interface functions:

<?phpinterface Fooable { function foo(?Fooable $f);}

Note that if the function itself defines the parameter type and has no default value, it cannot be omitted even if it can be empty. Otherwise, an error is triggered. As follows:

<? Phpfunction foo_nullable (? Bar $ bar) {} foo_nullable (new Bar); // feasible foo_nullable (null); // feasible foo_nullable (); // not feasible

However, if the parameter of the above function is defined?Bar $bar = null The third method is also feasible. Because= nullActually equivalent? For null type parameters, you can set null to the default value.

2. Simplified square brackets of list

We know that you can only use array() To define the array. After 5.4, the simplified Syntax of [] is added (five characters are omitted ).

<? Php // before 5.4 $ array = array (1, 2, 3); $ array = array ("a" => 1, "B" => 2, "c" => 3); // 5.4 and later $ array = [1, 2, 3]; $ array = ["a" => 1, "B" => 2, "c" => 3];

To solve another problem, if we want to assign the value of the array to different variables, we can uselist To achieve:

<?phplist($a, $b, $c) = $array;

Can I also use the shorthand?

<?php[$a, $b, $c] = $array;

As mentioned in the next featurelist Specifykey:

<?php["a" => $a, "b" => $b, "c" => $c] = $array;

PHP7.1 implements this feature. However, it should be noted that [] in the left value is not the abbreviation of array, it is list() .

But not just that, newlist() Can not only appear in the left value, but also inforeach Use in loop:

<?phpforeach ($points as ["x" => $x, "y" => $y]) { var_dump($x, $y);}

However, due to implementation problems,list()And [] cannot be nested with each other:

<? Php // invalid list ([$ a, $ B], [$ c, $ d]) = [1, 2], [3, 4]; // invalid [list ($ a, $ B), list ($ c, $ d)] = [1, 2], [3, 4]; // valid [[$ a, $ B], [$ c, $ d] = [[1, 2], [3, 4];

3. Allow specifying a key in the list

As mentioned above, the newlist() You can specify the key:

<?php$array = ["a" => 1, "b" => 2, "c" => 3];["a" => $a, "b" => $b, "c" => $c] = $array;

This is equivalent:

<?php$a = $array['a'];$b = $array['b'];$c = $array['c'];

The difference from the past is thatlist()The implementation is equivalent to the number format where the key can only be 0, 1, 2, 3, and the order cannot be adjusted. Run the following statement:

<?phplist($a, $b) = [1 => '1', 2 => '2'];

Will get PHP error: Undefined offset: 0... .

The new implementation can adjust the value assignment in the following ways:

<?phplist(1 => $a, 2 => $b) = [1 => '1', 2 => '2'];

Unlike arrays,list Hybrid format is not supportedkey, The following write method will trigger a parsing error:

<?php// Parse error: syntax error, ...list($unkeyed, "key" => $keyed) = $array;

More complex situations,list It also supports resolution in the composite form:

<?php$points = [ ["x" => 1, "y" => 2], ["x" => 2, "y" => 1]];list(list("x" => $x1, "y" => $y1), list("x" => $x2, "y" => $y2)) = $points;$points = [ "first" => [1, 2], "second" => [2, 1]];list("first" => list($x1, $y1), "second" => list($x2, $y2)) = $points;

And use it in a loop:

<?php$points = [ ["x" => 1, "y" => 2], ["x" => 2, "y" => 1]];foreach ($points as list("x" => $x, "y" => $y)) { echo "Point at ($x, $y)", PHP_EOL;}

Iv. void return type

PHP7.0 adds the feature of specifying the function return type, but the return type cannot be specifiedvoid, 7.1 of this feature is a supplement:

<?phpfunction should_return_nothing(): void { return 1; // Fatal error: A void function must not return a value}

Verification can be performed in either of the following cases:

<?phpfunction lacks_return(): void { // valid}function returns_nothing(): void { return; // valid}

Define the return typevoid The function cannot return values, even ifnull No way:

<?phpfunction returns_one(): void { return 1; // Fatal error: A void function must not return a value}function returns_null(): void { return null; // Fatal error: A void function must not return a value}

In additionvoid It is only applicable to the return type and cannot be used for parameter type declaration, or an error is triggered:

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

The Declaration of the return type in the class function cannot be overwritten by the quilt class; otherwise, an error is triggered:

<?phpclass Foo{ public function bar(): void { }}class Foobar extends Foo{ public function bar(): array { // Fatal error: Declaration of Foobar::bar() must be compatible with Foo::bar(): void }}

5. Set constant attributes

This feature is relatively simple, that is, constants in the current class can be used.public,private Andprotected Modified:

<? Phpclass Token {// The default constant is public const PUBLIC_CONST = 0; // The visible range of the custom constant is private const PRIVATE_CONST = 0; protected const PROTECTED_CONST = 0; public const PUBLIC_CONST_TWO = 0; // multiple constants can be declared at the same time with only one attribute private const FOO = 1, BAR = 2 ;}

In addition (interface) Can only bepublic Attribute:

<?phpinterface ICache { public const PUBLIC = 0; const IMPLICIT_PUBLIC = 1;}

To cope with changes, the implementation of the reflection class is also enriched accordingly.getReflectionConstant AndgetReflectionConstants Two methods are used to obtain additional attributes of a constant:

<?phpclass testClass { const TEST_CONST = 'test';}$obj = new ReflectionClass( "testClass" );$const = $obj->getReflectionConstant( "TEST_CONST" );$consts = $obj->getReflectionConstants();

6. Multi-condition catch

In the pasttry ... catch Statement, eachcatch Only one condition can be set:

<? Phptry {// Some code ...} catch (ExceptionType1 $ e) {// process ExceptionType1} catch (ExceptionType2 $ e) {// process ExceptionType2} catch (\ Exception $ e ){//...}

In the new implementationcatch Set multiple conditions in, equivalent to or in the form of judgment:

<? Phptry {// Some code ...} catch (ExceptionType1 | ExceptionType2 $ e) {// processing of ExceptionType1 and ExceptionType2} catch (\ Exception $ e ){//...}

Exception Handling is simplified.

Summary

The above is all the content of this article. I hope this article will help you learn or use PHP7.1. If you have any questions, please leave a message.

Appendix: Source RFC address

Nullable Types
Square bracket syntax for array destructuring assignment
Allow specifying keys in list ()
Generalize support of negative string offsets
Void Return Type
Class constant visibility modifiers
Multi catch

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.