Skip to content
Advertisement

Chaining Static Methods in PHP?

Is it possible to chain static methods together using a static class? Say I wanted to do something like this:

JavaScript

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

JavaScript

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

Advertisement

Answer

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement