2013年8月28日星期三

Lukas Smith: __toString() or not __toString()?


In Lukas Smith's latest post he looks at one of the magic methods that's built into PHP to help transform objects into strings - the __toString method. In the post he explores what it's for and what it might be used for.



The __toString() belongs to the family of methods and functions called "magic functions". They are magic because for the most part they do not get called explicitly but rather intercept operations. Unfortunately there are limits to its magic, specifically the only "context" the method is aware of is its design contract: to return a string. But its not clear what purpose that is. Should this be for some internal debugging or logging purposes? There one would be most interested in internal identifiers and object state. Is it for some frontend UI where the user will most likely be interested in some textual identifier that isn't too long as to not clutter the UI. There in lies the dilemma in the magic, while useful there is no way to ensure that the given context is passed on.


He looks at use cases for UI output (for consistent output) and contexts as well as the more internal-facing usage, like for logging and debugging purposes. Being able to get the context of the object as a string and pushed into a log at the time of error could be immensely helpful for debugging. He also links to some discussions happening on Twitter about the internal versus external uses of this magic method.


Link: http://pooteeweet.org/blog/0/2231#m2231

没有评论:

发表评论