• 技术文章 >后端开发 >php教程

    PHP5.5到PHP7.2新特性整理

    小云云小云云2018-03-31 11:20:31原创1245
    本文主要和大家分享PHP5.5到PHP7.2新特性整理,让大家对php的各个版本都有所了解,希望能帮助到大家。

    从PHP 5.5.x 移植到 PHP 5.6.x

    新特性

    使用表达式定义常量

    <?phpconst ONE = 1;const TWO = ONE * 2;class C {
        const THREE = TWO + 1;    const ONE_THIRD = ONE / self::THREE;    const SENTENCE = 'The value of THREE is '.self::THREE;
    }
    <?phpconst ARR = ['a', 'b'];echo ARR[0];

    使用 ... 运算符定义变长参数函数

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

    以上例程会输出:

    $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

    使用 ... 运算符进行参数展开

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

    以上例程会输出:

    6

    use function 以及 use const

    <?phpnamespace 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();
    }?>

    以上例程会输出:

    42
    Name\Space\f

    使用 hash_equals() 比较字符串避免时序攻击

    从PHP 5.6.x 移植到 PHP 7.0.x

    新特性

    标量类型声明

    <?php// Coercive modefunction sumOfInts(int ...$ints){
        return array_sum($ints);
    }
    var_dump(sumOfInts(2, '3', 4.1));

    以上例程会输出:

    int(9)

    返回值类型声明

    <?phpfunction arraysSum(array ...$arrays): array{
        return array_map(function(array $array): int {
            return array_sum($array);
        }, $arrays);
    }

    null合并运算符

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

    太空船操作符(组合比较符)

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

    通过 define() 定义常量数组

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

    Closure::call()

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

    以上例程会输出:

    1

    分组 use 声明

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

    生成器可以返回表达式

    整数除法函数 intp()


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

    新特性

    可为空(Nullable)类型

    <?phpfunction testReturn(): ?string{
        return 'elePHPant';
    }
    var_dump(testReturn());function testReturn(): ?string{
        return null;
    }
    var_dump(testReturn());function test(?string $name){
        var_dump($name);
    }
    test('elePHPant');
    test(null);
    test();

    以上例程会输出:

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

    Void 函数

    <?phpfunction 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);

    以上例程会输出:

    null
    int(2)
    int(1)

    Symmetric array destructuring

    <?php$data = [
        [1, 'Tom'],
        [2, 'Fred'],
    ];// list() stylelist($id1, $name1) = $data[0];// [] style[$id1, $name1] = $data[0];// list() styleforeach ($data as list($id, $name)) {    // logic here with $id and $name}// [] styleforeach ($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 伪类

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

    多异常捕获处理

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

    list()现在支持键名

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

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

    新特性

    新的对象类型

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

    扩展了参数类型

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

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

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

    http://php.net/manual/zh/appendices.php

    从PHP 5.5.x 移植到 PHP 5.6.x

    新特性

    使用表达式定义常量

    <?phpconst ONE = 1;const TWO = ONE * 2;class C {
        const THREE = TWO + 1;    const ONE_THIRD = ONE / self::THREE;    const SENTENCE = 'The value of THREE is '.self::THREE;
    }
    <?phpconst ARR = ['a', 'b'];echo ARR[0];

    使用 ... 运算符定义变长参数函数

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

    以上例程会输出:

    $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

    使用 ... 运算符进行参数展开

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

    以上例程会输出:

    6

    use function 以及 use const

    <?phpnamespace 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();
    }?>

    以上例程会输出:

    42
    Name\Space\f

    使用 hash_equals() 比较字符串避免时序攻击

    从PHP 5.6.x 移植到 PHP 7.0.x

    新特性

    标量类型声明

    <?php// Coercive modefunction sumOfInts(int ...$ints){
        return array_sum($ints);
    }
    var_dump(sumOfInts(2, '3', 4.1));

    以上例程会输出:

    int(9)

    返回值类型声明

    <?phpfunction arraysSum(array ...$arrays): array{
        return array_map(function(array $array): int {
            return array_sum($array);
        }, $arrays);
    }

    null合并运算符

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

    太空船操作符(组合比较符)

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

    通过 define() 定义常量数组

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

    Closure::call()

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

    以上例程会输出:

    1

    分组 use 声明

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

    生成器可以返回表达式

    整数除法函数 intp()


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

    新特性

    可为空(Nullable)类型

    <?phpfunction testReturn(): ?string{
        return 'elePHPant';
    }
    var_dump(testReturn());function testReturn(): ?string{
        return null;
    }
    var_dump(testReturn());function test(?string $name){
        var_dump($name);
    }
    test('elePHPant');
    test(null);
    test();

    以上例程会输出:

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

    Void 函数

    <?phpfunction 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);

    以上例程会输出:

    null
    int(2)
    int(1)

    Symmetric array destructuring

    <?php$data = [
        [1, 'Tom'],
        [2, 'Fred'],
    ];// list() stylelist($id1, $name1) = $data[0];// [] style[$id1, $name1] = $data[0];// list() styleforeach ($data as list($id, $name)) {    // logic here with $id and $name}// [] styleforeach ($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 伪类

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

    多异常捕获处理

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

    list()现在支持键名

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

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

    新特性

    新的对象类型

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

    扩展了参数类型

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

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

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

    相关推荐:

    PHP5各个版本的新功能和新特性总结

    以上就是PHP5.5到PHP7.2新特性整理的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:PHP5.5 PHP7.2 php
    上一篇:python如何实现php的global变量 下一篇:wampserver如何配置php网站多站点
    线上培训班

    相关文章推荐

    • 你知道这个PHP命令行选项解析库(pflag)吗?• 带你看懂PHP中的class定义类与成员属性方法• PHP中如何才能将时间日期格式化?怎么计算时间差?• 最详细的教你PHP时间戳与日期时间的转换• 一定搞得懂PHP中如何添加图片水印

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网