php7新特性

一。闭包调用 -- Closure::call()

  php7之前,想要动态的给一个对象添加方法时,可以通过Closure来复制一个闭包对象,并绑定到一个$this对象和类作用域,即 bindTo 。而PHP7增加了新特性Closure::call(), 可以通过call来暂时绑定一个闭包对象到$this对象并调用它。

  新建一个Test类

class Test{
    private $num = 1;
    public function __construct($n=0)
    {
        $this->num = $this->num+$n;
    }
    public function getNum(){
        return $this->num;
    }
}

  再来一个闭包

$f = function (){
    return $this->num = 9;
};

  然后new一个test对象

   临时绑定操作

   查看对象的num是否更改

   对象的私有属性num被更改,闭包对象被绑定到$this对象并被调用。

二。更多新特性参考官网:https://www.php.net/manual/zh/migration71.php

posted @ 2019-11-17 23:06  Python++  阅读(161)  评论(0编辑  收藏  举报