Chaining Static Methods in PHP?

前端 未结 16 2063
情歌与酒
情歌与酒 2020-11-27 14:25

Is it possible to chain static methods together using a static class? Say I wanted to do something like this:

$value = TestClass::toValue(5)::add(3)::subtrac         


        
16条回答
  •  [愿得一人]
    2020-11-27 14:57

    Here's another way without going through a getInstance method (tested on PHP 7.x):

    class TestClass
    {
        private $result = 0;
    
        public function __call($method, $args)
        {
            return $this->call($method, $args);
        }
    
        public static function __callStatic($method, $args)
        {
            return (new static())->call($method, $args);
        }
    
        private function call($method, $args)
        {
            if (! method_exists($this , '_' . $method)) {
                throw new Exception('Call undefined method ' . $method);
            }
    
            return $this->{'_' . $method}(...$args);
        }
    
        private function _add($num)
        {
            $this->result += $num;
    
            return $this;
        }
    
        private function _subtract($num)
        {
            $this->result -= $num;
    
            return $this;
        }
    
        public function result()
        {
            return $this->result;
        }
    }
    

    The class can be used as following:

    $res1 = TestClass::add(5)
        ->add(3)
        ->subtract(2)
        ->add(8)
        ->result();
    
    echo $res1 . PHP_EOL; // 14
    
    $res2 = TestClass::subtract(1)->add(10)->result();
    echo $res2 . PHP_EOL; // 9
    

提交回复
热议问题