John Davidson

oop - Chaining Static Methods in PHP?

0 comments
Message:


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



My Answer:
It is not possible to chain static methods together using a static class in PHP. Static methods do not have access to the "self" keyword, which is used to refer to the current class instance. In the example you provided, you would need to use a class instance instead of static methods in order to achieve the desired functionality.

Rate this post

4 of 5 based on 2383 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us