LoginSignup
7
1

More than 5 years have passed since last update.

メソッドチェインの終端で自動的に何かする小技

Posted at
(new Chain)->push(1)->push(2)->push(3);

のようなメソッドチェインの最後が実行された後に自動で処理を入れたりします。

<?php
class Chain
{
    private $last = false;

    private $arr = [];

    public function __destruct()
    {
        if ($this->last) {
            $this->fire();
        }
    }

    private function fire()
    {
        var_dump(implode(',', $this->arr));
    }

    public function push(int $val)
    {
        $this->last = false;
        $obj = clone $this;
        $obj->last = true;
        $obj->arr[] = $val;
        return $obj;
    }
}

// 最後の push(3) が返したオブジェクトのみ fire() が実行されます
(new Chain)->push(1)->push(2)->push(3); //=> 1,2,3

// 変数に入れると実行されません
$a = (new Chain)->push(1)->push(2)->push(3);
$b = $a->push(4);

// ↑の $a の続きです
$a->push(5); //=> 1,2,3,5

// ↑の $a の後に push(4) した $b の続きです
$b->push(6); //=> 1,2,3,4,6

内部 DSL のようなものを作るときに使えるかも?

7
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1