Home Backend Development PHP7 New features from PHP5.5 to PHP7.2

New features from PHP5.5 to PHP7.2

Mar 28, 2019 pm 05:17 PM
php7


1. Migrate from PHP 5.5.x to PHP 5.6.x

Use expressions to define constants

In previous versions of PHP, static values ​​had to be used to define constants, declare properties, and specify default values ​​for function parameters. You can now use numeric expressions including numbers, string literals, and other constants to define constants, declare properties, and set default values ​​for function parameters.

<?php
const ONE = 1;
const TWO = ONE * 2;
class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = &#39;The value of THREE is &#39;.self::THREE;
}
Copy after login

Now you can define constants of type array through the const keyword.

<?php
const ARR = [&#39;a&#39;, &#39;b&#39;];
echo ARR[0];
Copy after login

Use ... operators to define variable-length parameter functions

Now you can not rely on func_get_args(), Use ... operators to implement variable-length parameter functions.

<?php
function f($req, $opt = null, ...$params) {
    // $params 是一个包含了剩余参数的数组
    printf(&#39;$req: %d; $opt: %d; number of params: %d&#39;."\n",
           $req, $opt, count($params));
}
f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
?>
Copy after login

The above routine will output:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
Copy after login

Use ... operators for parameter expansion

When calling the function When using ... operators, expand arrays and traversable objects into function parameters. In other programming languages, such as Ruby, this is called the concatenation operator.

<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}
$operators = [2, 3];
echo add(1, ...$operators);
?>
Copy after login

The above routine will output:

6
Copy after login

use function and use const

use operator has been extended to support Import external functions and constants into the class. The corresponding structures are use function and use const.

<?php
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
}
namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;
    echo FOO."\n";
    f();
}
?>
Copy after login

The above routine will output:

42
Name\Space\f
Copy after login

Use hash_equals() Compare strings to avoid timing attacks

2. From PHP 5.6 .x Ported to PHP 7.0.x

Scalar type declaration

Scalar type declarations have two modes: mandatory (default) and strict mode. The following type parameters are now available (either in forced or strict mode): string, int, float, and bool.

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}
var_dump(sumOfInts(2, &#39;3&#39;, 4.1));
Copy after login

The above routine will output:

int(9)
Copy after login

Return value type declaration

PHP 7 adds support for return type declaration. Similar to the parameter type declaration, the return type declaration specifies the type of the function's return value. The available types are the same as those available in the parameter declaration.

<?php
function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}
Copy after login

null coalescing operator

Due to the large number of situations where ternary expressions and isset() are used simultaneously in daily use, we added the null coalescing operator ( ??) This syntactic sugar. If the variable exists and is not NULL, it returns its own value, otherwise it returns its second operand.

<?php
// Fetches the value of $_GET[&#39;user&#39;] and returns &#39;nobody&#39; if it does not exist.
$username = $_GET[&#39;user&#39;] ?? &#39;nobody&#39;;
// This is equivalent to:
$username = isset($_GET[&#39;user&#39;]) ? $_GET[&#39;user&#39;] : &#39;nobody&#39;;
// Coalesces can be chained: this will return the first defined value out of $_GET[&#39;user&#39;], $_POST[&#39;user&#39;], and &#39;nobody&#39;.
$username = $_GET[&#39;user&#39;] ?? $_POST[&#39;user&#39;] ?? &#39;nobody&#39;;
?>
Copy after login

Spaceship operator (combined 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. The principle of comparison follows PHP's regular comparison rules.

<?php
// 整数
echo 1 <=> &#39;1&#39;; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// 浮点数
echo &#39;1.50&#39; <=> 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
?>
Copy after login

Define constant arrays via define()

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

define(&#39;ANIMALS&#39;, [
    &#39;dog&#39;,
    &#39;cat&#39;,
    &#39;bird&#39;
]);
echo ANIMALS[1]; // 输出 "cat"
Copy after login

Closure::call()

Closure::call() Now has better performance, short and concise temporary binding Closure a method on the object and call it.

<?php
class A {private $x = 1;}
// PHP 7 之前版本的代码
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, &#39;A&#39;); // 中间层闭包
echo $getX();
// PHP 7+ 及更高版本的代码
$getX = function() {return $this->x;};
echo $getX->call(new A);
Copy after login

The above routine will output:

1
Copy after login

Group use declaration

Classes, functions and constants imported from the same namespace can now be passed through a single use The statement is imported at once.

<?php
// PHP 7 之前的代码
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;
// PHP 7+ 及更高版本的代码
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};
?>
Copy after login

Generators can return expressions

This feature builds on the generator feature introduced in PHP 5.5 version. It allows an expression to be returned by using the return syntax in a generator function (but does not allow the return of a reference value). The return value of the generator can be obtained by calling the Generator::getReturn() method, but this method can only be used when generating Called once after the processor has finished generating work.

Integer division function intdiv()

##3. Migrating from PHP 7.0.x to PHP 7.1.x

Nullable types

The types of parameters and return values ​​can now be nullable by adding a question mark before the type. When this feature is enabled, the parameters passed in or the result returned by the function are either of the given type or null .

<?php
function testReturn(): ?string
{
    return &#39;elePHPant&#39;;
}
var_dump(testReturn());
function testReturn(): ?string
{
    return null;
}
var_dump(testReturn());
function test(?string $name)
{
    var_dump($name);
}
test(&#39;elePHPant&#39;);
test(null);
test();
Copy after login

The above routine will output:

string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...
Copy after login

Void function

A new return value type void is introduced. Methods whose return values ​​are declared of type void either simply omit the

return statement, 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);
Copy after login

The above routine will output:

null
int(2)
int(1)
Symmetric array destructuring
Copy after login

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

<?php
$data = [
    [1, &#39;Tom&#39;],
    [2, &#39;Fred&#39;],
];
// 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
}
Copy after login

Class constant visibility

Now supports setting the visibility of class constants.

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

iterable<strong></strong> Pseudo class

现在引入了一个新的被称为iterable的伪类 (与callable类似)。 这可以被用在参数或者返回值类型中,它代表接受数组或者实现了Traversable接口的对象。 至于子类,当用作参数时,子类可以收紧父类的iterable类型到array 或一个实现了Traversable的对象。对于返回值,子类可以拓宽父类的 array或对象返回值类型到iterable。

<?php
function iterator(iterable $iter) : iterable
{
    foreach ($iter as $val) {
        //
    }
}
Copy after login

多异常捕获处理

一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用。

<?php
try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
}
Copy after login

list()现在支持键名

现在list()和它的新的[]语法支持在它内部去指定键名。这意味着它可以将任意类型的数组 都赋值给一些变量(与短数组语法类似)

<?php
$data = [
    ["id" => 1, "name" => &#39;Tom&#39;],
    ["id" => 2, "name" => &#39;Fred&#39;],
];
// 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
}
Copy after login

四、从PHP 7.1.x 移植到 PHP 7.2.x

新的对象类型

这种新的对象类型, object, 引进了可用于逆变(contravariant)参数输入和协变(covariant)返回任何对象类型。

<?php
function test(object $obj) : object
{
    return new SplQueue();
}
test(new StdClass());
Copy after login

允许重写抽象方法(Abstract method)

当一个抽象类继承于另外一个抽象类的时候,继承后的抽象类可以重写被继承的抽象类的抽象方法。

abstract class A
{
    abstract function test(string $s);
}
abstract class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;
}
Copy after login

扩展了参数类型

重写方法和接口实现的参数类型现在可以省略了。不过这仍然是符合LSP,因为现在这种参数类型是逆变的。

interface A
{
    public function Test(array $input);
}
class B implements A
{
    public function Test($input){} // type omitted for $input
}
Copy after login

允许分组命名空间的尾部逗号

命名空间可以在PHP 7中使用尾随逗号进行分组引入。

use Foo\Bar\{
    Foo,
    Bar,
    Baz,
};
Copy after login



The above is the detailed content of New features from PHP5.5 to PHP7.2. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? Apr 02, 2024 pm 07:39 PM

To resolve the plugin not showing installed issue in PHP 7.0: Check the plugin configuration and enable the plugin. Restart PHP to apply configuration changes. Check the plugin file permissions to make sure they are correct. Install missing dependencies to ensure the plugin functions properly. If all other steps fail, rebuild PHP. Other possible causes include incompatible plugin versions, loading the wrong version, or PHP configuration issues.

How to install mongo extension in php7.0 How to install mongo extension in php7.0 Nov 21, 2022 am 10:25 AM

How to install the mongo extension in php7.0: 1. Create the mongodb user group and user; 2. Download the mongodb source code package and place the source code package in the "/usr/local/src/" directory; 3. Enter "src/" directory; 4. Unzip the source code package; 5. Create the mongodb file directory; 6. Copy the files to the "mongodb/" directory; 7. Create the mongodb configuration file and modify the configuration.

How to solve the problem when php7 detects that the tcp port is not working How to solve the problem when php7 detects that the tcp port is not working Mar 22, 2023 am 09:30 AM

In php5, we can use the fsockopen() function to detect the TCP port. This function can be used to open a network connection and perform some network communication. But in php7, the fsockopen() function may encounter some problems, such as being unable to open the port, unable to connect to the server, etc. In order to solve this problem, we can use the socket_create() function and socket_connect() function to detect the TCP port.

PHP Server Environment FAQ Guide: Quickly Solve Common Problems PHP Server Environment FAQ Guide: Quickly Solve Common Problems Apr 09, 2024 pm 01:33 PM

Common solutions for PHP server environments include ensuring that the correct PHP version is installed and that relevant files have been copied to the module directory. Disable SELinux temporarily or permanently. Check and configure PHP.ini to ensure that necessary extensions have been added and set up correctly. Start or restart the PHP-FPM service. Check the DNS settings for resolution issues.

How to install and deploy php7.0 How to install and deploy php7.0 Nov 30, 2022 am 09:56 AM

How to install and deploy php7.0: 1. Go to the PHP official website to download the installation version corresponding to the local system; 2. Extract the downloaded zip file to the specified directory; 3. Open the command line window and go to the "E:\php7" directory Just run the "php -v" command.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

Record once and use strace to diagnose the problem of PHP occupying too much system resources. Record once and use strace to diagnose the problem of PHP occupying too much system resources. May 03, 2024 pm 04:31 PM

Local environment: redhat6.7 system. nginx1.12.1, php7.1.0, the code uses the yii2 framework problem: the local web site needs to use the elasticsearch service. When PHP uses elasticsearch built on a local server, the local load is normal. When I use AWS's elasticsearch service, the load on the local server is often too high. Check the nginx and php logs and find no exceptions. The number of concurrent connections in the system is also not high. At this time, I thought of a strace diagnostic tool that our boss told me. Debugging process: Find a php sub-process idstrace-

See all articles