PHP 7 New Features (Continuously Updated)

PHP

PHP 8 is released, recommended to check:

PHP 8新特性


There are some obvious functions that you can learn about and make some notes.

PHP 7.4 updates

Arrow Function 2.0

RFC Simplified arrow functions

function array_values_from_keys($arr, $keys) {
return array_map(function ($x) use ($arr) { return $arr[$x]; }, $keys);
}

After simplification:

function array_values_from_keys($arr, $keys) {
return array_map(fn($x) => $arr[$x], $keys);
}

Note: You still need to retain the fn keyword

Type Properties 2.0

RFC Now you can add a type to the value defined by the protected attribute value in the class (more like a strongly typed language like java)

<?php
class A
{
protected $Name
public function getName(){}
}

After PHP 7.4:

<?php
class A
{
// 指定 $name 为字符类型
protected string $Name
public function getName(){}
}

Null coalescing operator

RFC

To put it simply, ?? can be used as ??=

// 下面两种写法是一样的
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// 这是php7.4独有的写法
$this->request->data['comments']['user_id'] ??= 'value';

Summary

The visible updates are the above. In addition, it should be noted that this version has deprecated many things. For details, you can see this list:

https://wiki.php.net/rfc/deprecations_php_7_4

Some others: Preloading/FFI/Covariant Returns and Contravariant Parameters can refer to the official documentation https://www.php.net/ChangeLog-7.php#PHP_7_4

PHP 7.3

New function array_key_first() array_key_last()

<?php
// 当 key 为字符串时
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 'a'); // true
assert($lastKey === 'c'); // true
// 当 key 为数字时
$array = [1 => 'a', 2 => 'b', 3 => 'c'];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === 1); // true
assert($lastKey === 3); // true
// 空数组
$array = [];
$firstKey = array_key_first($array);
$lastKey = array_key_last($array);
assert($firstKey === null); // true
assert($lastKey === null); // true

Support multiple variables in function calls

$foo = 'hello';
$bar = 'php';
$baz = '!';
unset(
$foo,
$bar,
$baz,
);

Change Log

https://secure.php.net/ChangeLog-7.php#7.3.0

rfc

https://wiki.PHP.net/rfc#PHP_73

PHP 7.2

Allow trailing commas for grouped namespaces

Namespaces can be grouped in PHP 7 using a trailing comma.

<?php
use Foo\Bar\{
Foo,
Bar,
Baz,
};

Others

http://PHP.net/manual/zh/migration72.new-features.PHP

rfc

https://wiki.PHP.net/rfc#PHP_72

PHP 7.1

Nullable type

<?php
function testReturn(): ?string
{
return 'elePHPant';
}
var_dump(testReturn()); // string(10) "elePHPant"
function testReturn(): ?string
{
return null;
}
var_dump(testReturn()); // NULL
function test(?string $name)
{
var_dump($name);
}
test('elePHPant'); // string(10) "elePHPant"
test(null); // NULL
test(); // Uncaught Error: Too few arguments to function test(), 0 passed in...

In fact, the number ? is used to represent that the function parameters and return values are either of the specified type or null

Void function

A new return value type void is introduced. Methods whose return values ​​are declared of type void either omit the return statement altogether or use an empty return statement. NULL is not a legal return value for void functions.

<?php
function swap(&$left, &$right) : void
{
if ($left === $right) {
return;
}
$tmp = $left;
$left = $right;
$right = $tmp;
}
$a = 1;
$b = 2;
var_dump(swap($a, $b), $a, $b);

The above result output

null
int(2)
int(1)

Square bracket abbreviation for list

The short array syntax [] is now an alternative to the list() syntax and can be used to assign the value of an array to some variable (including in a foreach).

<?php
$data = [
[1, 'Tom'],
[2, 'Fred'],
];
// list() style
list($id1, $name1) = $data[0];
// [] style
[$id1, $name1] = $data[0];
// list() style
foreach ($data as list($id, $name)) {
// logic here with $id and $name
}
// [] style
foreach ($data as [$id, $name]) {
// logic here with $id and $name
}

list() now supports key names

list() and its new [] syntax now support specifying key names within it. This means that it can assign any type of array to some variable (similar to the short array syntax)

<?php
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
// list() style
list("id" => $id1, "name" => $name1) = $data[0];
// [] style
["id" => $id1, "name" => $name1] = $data[0];
// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
// logic here with $id and $name
}
// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
// logic here with $id and $name
}

Class constant visibility

Setting the visibility of class constants is now supported.

<?php
class ConstDemo
{
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}

Support negative string offsets

All string operation functions that support offsets now support accepting negative numbers as offsets, including operating string subscripts through [] or {}. In this case, a negative offset is interpreted as an offset from the end of the string.

<?php
var_dump("abcdef"[-2]); // string(1) "3"
var_dump(strpos("aabbcc", "b", -3)); // int(3)
<?php
$string = 'bar';
echo "The last character of '$string' is '$string[-1]'.\n";
//输出: The last character of 'bar' is 'r'.

Others

http://PHP.net/manual/zh/migration71.new-features.PHP

rfc

https://wiki.PHP.net/rfc#PHP_71

PHP 7.0

??Operator

This is more commonly used, example:

<?php
// PHP 7
$data = $_GET['type'] ?? '1';
// 等于
$data = isset($_GET['type']) ? $_GET['type'] : 1;

Parameter and function return value type declaration

<?php
// PHP 7
function sum(int $number) : int {
return $number + $number;
}
echo sum(1); // 2
// 等于
function sum($number){
return $number + $number;
}
echo sum(1); // 2

This way of specifying data types can avoid some problems caused by PHP’s implicit type conversion. It feels like it provides an option for a strongly typed language.

PHP7 provides a strict mode, which is better used with strict mode. If an unspecified type is returned in non-strict mode, PHP will still perform implicit conversion by default. For example:

<?php
// 非严格模式下
function sum(int $number) : int {
return $number + 1.8;
}
echo sum(1); // 2
// 等于
$data = 2.8;
echo (int)$data // 2

If a non-specified type is returned in strict mode, PHP will report a PHP Fatal error. For example:

<?php
declare(strict_types=1);
function sum(int $number) : int
{
return $number + 1;
}
$a = sum(1.8);
print_r($a);

Running results:

PHP Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in /path/Untitled 2.PHP:4
Stack trace:
...

use batch declaration

<?php
use App\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Spaceship operator (combination comparison operator)

The spaceship operator is used to compare two expressions. It returns -1, 0 or 1 when $a is less than, equal to or greater than $b respectively.

<?php
// 整数
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// 浮点数
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// 字符串
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

This comparison feels useless.

Define constant arrays through define()

Constants of type Array can now be defined via define(). In PHP5.6 it can only be defined via const.

<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // 输出 "cat"

Generator delegate

Now, you can automatically delegate a generator to other generators, Traversable objects, or arrays simply by using yield from in the outermost generator.

<?php
function gen()
{
yield 1;
yield 2;
yield from gen2();
}
function gen2()
{
yield 3;
yield 4;
}
foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
// result
1
2
3
4

Integer division function intdiv()

The newly added function intdiv() is used to perform integer division operations.

<?php
var_dump(intdiv(10, 3)); // int(3)

Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) Function

Two new cross-platform functions have been added: random_bytes() and random_int() to generate high-security random strings and random integers.

Other features

http://PHP.net/manual/zh/migration70.new-features.PHP