在PHP中链接静态方法?

在PHP中链接静态方法?,第1张

在PHP中链接静态方法?

我喜欢上面Camilo提供的解决方案,基本上是因为您要做的只是更改静态成员的值,并且因为您确实想要链接(即使它只是句法糖),所以实例化TestClass可能是最好的方法。

如果您想限制类的实例化,我建议使用Singleton模式:

class TestClass{       public static $currentValue;    private static $_instance = null;    private function __construct () { }    public static function getInstance ()    {        if (self::$_instance === null) { self::$_instance = new self;        }        return self::$_instance;    }    public function toValue($value) {        self::$currentValue = $value;        return $this;    }    public function add($value) {        self::$currentValue = self::$currentValue + $value;        return $this;    }    public function subtract($value) {        self::$currentValue = self::$currentValue - $value;        return $this;    }    public function result() {        return self::$currentValue;    }}// Example Usage:$result = TestClass::getInstance ()    ->toValue(5)    ->add(3)    ->subtract(2)    ->add(8)    ->result();


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5014899.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-15
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存