Where and why do we use __toString() in PHP?

后端 未结 10 1698
星月不相逢
星月不相逢 2021-01-01 10:34

I understand how it works but why would we practically use this?



        
10条回答
  •  Happy的楠姐
    2021-01-01 10:51

    It's just a standardized method to produce a string representation of an object. Your random_method approach works if you assume all objects in your program uses that same method, which might not be the case if you use third party libraries.

    You don't need the magic method, but it provides convenience, as you'll never really have to call it explicitly.

    Also, if PHP should internally ever want to turn your object into text, it knows how to do that.

提交回复
热议问题