如何写一个chain

2020-04-09  本文已影响0人  sorry510
class Unit
{

    public static function test($arg)
    {
        return 1;
    }

    // 返回一个链式调用类
    public static function chain($arg)
    {
        return (new class(self::class, $arg)
        {
            private $arg;
            private $originClass;

            public function __construct($originClass, $arg)
            {
                $this->arg= $arg;
                $this->originClass = $originClass;
            }

            public function __call($name, $args)
            {
                $args[] = $this->arg; // 追加str
                $this->arg= call_user_func_array([$this->originClass, $name], $args);
                if (is_string($this->arg)) {
                    return $this;
                } else {
                    return $this->arg;
                }
            }

            public function value()
            {
                return $this->arg;
            }

            public function __toString()
            {
                return $this->arg;
            }
        });
    }
}
上一篇下一篇

猜你喜欢

热点阅读