Chaining Static Methods in PHP?

前端 未结 16 2128
情歌与酒
情歌与酒 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 15:02

    Technically you can call a static method on an instance like $object::method() in PHP 7+, so returning a new instance should work as a replacement for return self. And indeed it works.

    final class TestClass {
        public static $currentValue;
    
        public static function toValue($value) {
            self::$currentValue = $value;
            return new static();
        }
    
        public static function add($value) {
            self::$currentValue = self::$currentValue + $value;
            return new static();
        }
    
        public static function subtract($value) {
            self::$currentValue = self::$currentValue - $value;
            return new static();
        }
    
        public static function result() {
            return self::$currentValue;
        }
    }
    
    $value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
    
    var_dump($value);
    

    Outputs int(14).

    This about same as returning __CLASS__ as used in other answer. I rather hope no-one ever decides to actually use these forms of API, but you asked for it.

提交回复
热议问题