tap函数的日常使用

Laravel框架
330
0
0
2022-04-12

tap解释

function tap($value, $callback = null)
{
  /*
  if (is_null($callback)) {
      return new HigherOrderTapProxy($value);
  }
  */
  $callback($value);
  return $value;
}

参数 传递给 闭包,并且返回 参数

(关于 HigherOrderTapProxy 百度一下把,很简单,不是本篇要吹的内容)

日常使用

一般都是跟对象打交道,这里要说明下: 对象引用传值的

例如:

$user = new User();
$user->id = 1;
$callback = function ($user){
    $user->id = 999;
};
$callback($user);
echo $user->id; // 999

阅读量增加

$article = tap(Article::find(1),function ($article) {
    $article->increment('view');
});

流接口模式

    public function setData($data){

        // 正常
        $this->data = $data;return $this;

        //  tap 
        return tap($this,function ($hello) use ($data) {
        // 这个$hello就是闭包外面的$this  闭包内的$this也是闭包外的$this(类)
            $this->data = $data;
        });

        // php8写法 
       return tap($this,fn() => $this->data = $data);
    }

凑个数

用tap来写一些骚写法