(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 のようなものを作るときに使えるかも?