PHP 7.1 new features at a glance
Nullable type
Nullable type is mainly used for parameter type declaration and function return value declaration.
The main two 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. What it means is to use the form of ? to indicate 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 interface functions:
<?php interface Fooable { function foo(?Fooable $f);}
But there is one thing to note: if the function itself defines the parameter type and has no default value, even if it is nullable , cannot be omitted, otherwise an error will be triggered. As follows:
<?php function foo_nullable(?Bar $bar) {} foo_nullable(new Bar); // 可行foo_nullable(null); // 可行foo_nullable(); // 不可行
But if the parameters of the above function are defined in the form of ?Bar $bar = null, the third way of writing is also feasible. Because = null is actually equivalent to a superset of ? , for nullable type parameters, null can be set as the default value.
The square bracket abbreviation of list
We know that before PHP5.4, arrays could only be defined through array(), which was added after 5.4 [] is a simplified way of writing (it is still very practical to omit 5 characters).
<?php // 5.4 之前$array = array(1, 2, 3);$array = array("a" => 1, "b" => 2, "c" => 3); // 5.4 及之后$array = [1, 2, 3];$array = ["a" => 1, "b" => 2, "c" => 3];
Extended to another question, if we want to assign the value of the array to different variables, it can be achieved through list:
<?php list($a, $b, $c) = $array;
Can it also be achieved through the abbreviation of [] Woolen cloth?
<?php [$a, $b, $c] = $array;
And the list specified key mentioned in the next feature:
<?php ["a" => $a, "b" => $b, "c" => $c] = $array;
PHP7.1 implements this feature. But it should be noted that the [] that appears in the lvalue is not the abbreviation of array, but the abbreviation of list().
But that’s not all, the new list() implementation can not only appear in lvalues, but can also be used in foreach loops:
<?php foreach ($points as ["x" => $x, "y" => $y]) { var_dump($x, $y);
However, due to implementation issues, list() and [] cannot be used nested in each other:
<?php // 不合法 list([$a, $b], [$c, $d]) = [[1, 2], [3, 4]]; // 不合法 [list($a, $b), list($c, $d)] = [[1, 2], [3, 4]]; // 合法 [[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];
Allows the key to be specified in the list
As mentioned above, new The key can be specified in the implementation of list():
<?php $array = ["a" => 1, "b" => 2, "c" => 3];["a" => $a, "b" => $b, "c" => $c] = $array;
This is equivalent to:
<?php $a = $array['a'];$b = $array['b'];$c = $array['c'];
The difference from the past is that the previous implementation of list() is equivalent to the key being only 0 , 1, 2, 3 and the order cannot be adjusted. Execute the following statement:
<?php list($a, $b) = [1 => '1', 2 => '2'];
will get the error PHP error: Undefined offset: 0... .
The new implementation can adjust the assignment in the following ways:
<?php list(1 => $a, 2 => $b) = [1 => '1', 2 => '2'];
Unlike arrays, list does not support mixed keys. The following writing will trigger a parsing error. :
<?php // Parse error: syntax error, ...list($unkeyed, "key" => $keyed) = $array;
For more complex situations, list also supports composite form parsing:
<?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 used in loops:
<?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;}
void return type
PHP7 .0 adds the feature of specifying function return type, but the return type cannot be specified as void. This feature of 7.1 is a supplement:
<?php function should_return_nothing(): void { return 1; // Fatal error: A void function must not return a value}
The following two situations can be verified:
<?php function lacks_return(): void { // valid} function returns_nothing(): void { return; // valid}
A function defined with a return type of void cannot have a return value, even if it returns null:
<?php function 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 addition, void is only applicable to the return type and cannot be used for parameter type declaration, or it will trigger an error:
<?php function foobar(void $foo) { // Fatal error: void cannot be used as a parameter type}
The declaration of return type in a class function cannot be overridden by a subclass, otherwise an error will be triggered:
<?php class 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 }}
Class constant attribute setting
This feature It is relatively simple to say, that is, the constants in the class now support the use of public, private and protected modifications:
<?php class Token { // 常量默认为 public const PUBLIC_CONST = 0; // 可以自定义常量的可见范围 private const PRIVATE_CONST = 0; protected const PROTECTED_CONST = 0; public const PUBLIC_CONST_TWO = 0; // 多个常量同时声明只能有一个属性 private const FOO = 1, BAR = 2;}
In addition, the constants in the interface (interface) can only be public attributes:
<?php interface ICache { public const PUBLIC = 0; const IMPLICIT_PUBLIC = 1;}
In order to cope with the changes, the implementation of the reflection class has also been enriched accordingly, and two methods getReflectionConstant and getReflectionConstants have been added to obtain additional attributes of constants:
<?php class testClass { const TEST_CONST = 'test'; } $obj = new ReflectionClass( "testClass" ); $const = $obj->getReflectionConstant( "TEST_CONST" ); $consts = $obj->getReflectionConstants();
Multi-condition catch
In the past In the try...catch statement, each catch can only set one conditional judgment:
<?php try { // Some code... } catch (ExceptionType1 $e) { // 处理 ExceptionType1} catch (ExceptionType2 $e) { // 处理 ExceptionType2} catch (Exception $e) { // ...}
In the new implementation, multiple conditions can be set in one catch, which is equivalent to the form judgment of or:
<?php try { // Some code...} catch (ExceptionType1 | ExceptionType2 $e) { // 对于 ExceptionType1 和 ExceptionType2 的处理} catch (Exception $e) { // ...}
The above is the list of new features of PHP 7.1. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
