bindTo和bind函数的使用介绍

bind和bindTo函数两者的区别不大,只是bind是静态函数,而bindTo是非静态函数

主要作用:复制一个闭包,绑定指定的$this对象和类作用域。

根据传递的参数不同可以分为几种情况:
  1、只绑定$this对象(在闭包中,只可以使用$this,不可以使用static)
  2、只绑定类作用域(在闭包中,只可以使用static,不可以使用$this)
  3、同时绑定$this对象和类作用域(在闭包中,可以使用$this和static)

 public function bindTo(?object $newThis, object|string|null $newScope = 'static') {}

bindTo函数:
  第一个参数如果传递null,则闭包函数中无法使用$this;传递类的实例,则可以使用$this
  第二个参数如果传递null或不传,则闭包函数中无法使用static;传递类的作用域,则可以使用static

    public static function bind(Closure $closure, ?object $newThis, object|string|null $newScope = 'static') {}

bind函数:第一个参数是一个闭包函数,其他两个参数使用和bindTo类似;

posted @ 2021-10-16 10:15  风哀伤  阅读(256)  评论(0编辑  收藏  举报