Alex Rivera | Logout

Chaining Static Methods in PHP?

Asked 2008-09-24T03:32:13.147
63

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

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

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).

Edit
Report

2 Answers

11

If toValue(x) returns an object, you could do like this:

$value = TestClass::toValue(5)->add(3)->substract(2)->add(8);

Providing that toValue returns a new instance of the object, and each next method mutates it, returning an instance of $this.

answered 2008-09-24T03:47:03.567
0

No, this won't work. The :: operator needs to evaluate back to a class, so after the TestClass::toValue(5) evaluates, the ::add(3) method would only be able to evaluate on the answer of the last one.

So if toValue(5) returned the integer 5, you would basically be calling int(5)::add(3) which obviously is an error.

answered 2008-09-24T03:40:25.063

Your Answer