在 PHP 中链接静态方法? [英] Chaining Static Methods in PHP?

查看:27
本文介绍了在 PHP 中链接静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用静态类将静态方法链接在一起?假设我想做这样的事情:

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)::subtract(2)::add(8)::result();

...显然我希望 $value 被分配数字 14.这可能吗?

. . . and obviously I would want $value to be assigned the number 14. Is this possible?

更新:它不起作用(你不能返回self"——这不是一个实例!),但这就是我的想法:

Update: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:

class TestClass {
    public static $currentValue;

    public static function toValue($value) {
        self::$currentValue = $value;
    }

    public static function add($value) {
        self::$currentValue = self::$currentValue + $value;
        return self;
    }

    public static function subtract($value) {
        self::$currentValue = self::$currentValue - $value;
        return self;
    }

    public static function result() {
        return self::$value;
    }
}

解决这个问题后,我认为简单地使用类实例而不是尝试链接静态函数调用会更有意义(这看起来不可能,除非可以以某种方式调整上面的示例).

After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).

推荐答案

我喜欢上面 Camilo 提供的解决方案,基本上是因为你所做的只是改变静态成员的值,而且你确实想要链接(甚至虽然它只是语法糖),那么实例化 TestClass 可能是最好的方法.

I like the solution provided by Camilo above, essentially since all you're doing is altering the value of a static member, and since you do want chaining (even though it's only syntatic sugar), then instantiating TestClass is probably the best way to go.

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

I'd suggest a Singleton pattern if you want to restrict instantiation of the class:

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();

这篇关于在 PHP 中链接静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆