Chaining Static Methods in PHP?

前端 未结 16 2065
情歌与酒
情歌与酒 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条回答
  •  -上瘾入骨i
    2020-11-27 14:41

    Use PHP 7! If your web provider cannot --> change provider! Don't lock in past.

    final class TestClass {
        public static $currentValue;
    
        public static function toValue($value) {
            self::$currentValue = $value;
            return __CLASS__;
        }
    
        public static function add($value) {
            self::$currentValue = self::$currentValue + $value;
            return __CLASS__;
        }
    
        public static function subtract($value) {
            self::$currentValue = self::$currentValue - $value;
            return __CLASS__;
        }
    
        public static function result() {
            return self::$currentValue;
        }
    }
    

    And very simple use:

    $value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result();
    
    var_dump($value);
    

    Return (or throw error):

    int(14)
    

    completed contract.

    Rule one: most evolved and maintainable is always better.

提交回复
热议问题