Chaining Static Methods in PHP?

前端 未结 16 2080
情歌与酒
情歌与酒 2020-11-27 14:25

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)::subtrac         


        
16条回答
  •  萌比男神i
    2020-11-27 14:39

    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.

提交回复
热议问题