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

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

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



        
10条回答
  •  醉梦人生
    2021-01-01 10:49

    You don't "need" it. But defining it allows your object to be implicitly converted to string, which is convenient.

    Having member functions that echo directly is considered poor form because it gives too much control of the output to the class itself. You want to return strings from member functions, and let the caller decide what to do with them: whether to store them in a variable, or echo them out, or whatever. Using the magic function means you don't need the explicit function call to do this.

提交回复
热议问题