search
HomeBackend DevelopmentPHP TutorialPHP5.5 ~ PHP7.2 new features organized

This article introduces the new features of PHP5.5 ~ PHP7.2. Friends in need can refer to it

Porting from PHP 5.5.x to PHP 5.6.x

New Features

Use expressions to define constants

  • In previous versions of PHP, you had to use static values ​​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;
}
  • You can now define constants of type array through the const keyword.

<?php
const ARR = [&#39;a&#39;, &#39;b&#39;];

echo ARR[0];

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

  • Now you can not rely on func_get_args(), Use the ... operator 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);
?>

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

Use the ... operator for parameter expansion

  • When calling a function, use the... operator to 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);
?>

The above routine will output:

6

use function and use const

  • use operator has been expanded To support importing external functions and constants into classes. 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();
}
?>

The above routine will output:

42
Name\Space\f

Use hash_equals() to compare strings to avoid timing attacks

Ported from PHP 5.6.x to PHP 7.0.x

New features

Scalar type declaration

  • There are two modes for scalar type declaration: 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));

The above routine will output:

int(9)

Return value type declaration

  • PHP 7 adds a return type declaration support. 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);
}

null coalescing operator

  • Since there are a lot of situations where ternary expressions and isset() are used simultaneously in daily use, we add The syntactic sugar of null coalescing operator (??) is added. 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;;
?>

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
?>

Defining 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"

Closure::call()

  • Closure::call() now has better performance, short and crisp temporary bindings 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);

The above routine will output:

1

Groupinguse Statement

  • From the same namespace Imported classes, functions, and constants can now be imported all at once with a single use statement.

<?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};
?>

Generators can return expressions

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

Integer division function intp()


Ported from PHP 7.0.x to PHP 7.1.x

New features

Nullable type

  • The types of parameters and return values ​​can now be allowed to be null 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();

The above routine will output:

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

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 routine will output:

null
int(2)
int(1)

Symmetric array destructuring

  • 短数组语法([])现在作为list()语法的一个备选项,可以用于将数组的值赋给一些变量(包括在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
}

类常量可见性

  • 现在起支持设置类常量的可见性。

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

iterable 伪类

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

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

多异常捕获处理

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

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

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
}

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

新特性

新的对象类型

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

<?php

function test(object $obj) : object
{
    return new SplQueue();
}

test(new StdClass());

允许重写抽象方法(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;
}

扩展了参数类型

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

interface A
{
    public function Test(array $input);
}

class B implements A
{
    public function Test($input){} // type omitted for $input
}

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

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

use Foo\Bar\{
    Foo,
    Bar,
    Baz,
};



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

Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.