News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Lukas Smith:
__toString() or not __toString()?
August 28, 2013 @ 09:14:39

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.

0 comments voice your opinion now!
tostring magicmethod usecase internal external

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

blog comments powered by Disqus

Similar Posts

Symfony Blog: Push it to the limits - Symfony2 for High Performance needs

Alexey Zakhlestin's Blog: on PHP's webserver

Internet Super Hero Blog: Debugging ext/mysqli and mysqlnd

Stubbles Blog: State of annotations in the PHP world

Micheal Kimsal's Blog: Symfony __toString() generation


Community Events





Don't see your event here?
Let us know!


series framework list interview podcast laravel release install update zendserver language deployment library opinion introduction package community symfony api tips

All content copyright, 2014 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework