Chaining Static Methods in PHP?

前端 未结 16 2129
情歌与酒
情歌与酒 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:40

    People are overcomplicating this like crazy.

    Check this out:

    class OopClass
    {
        public $first;
        public $second;
        public $third;
    
        public static function make($first)
        {
            return new OopClass($first);
        }
    
        public function __construct($first)
        {
            $this->first = $first;
        }
    
        public function second($second)
        {
            $this->second = $second;
            return $this;
        }
    
        public function third($third)
        {
            $this->third = $third;
            return $this;
        }
    }
    

    Usage:

    OopClass::make('Hello')->second('To')->third('World');
    

提交回复
热议问题