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

Internet Super Hero Blog: Debugging ext/mysqli and mysqlnd

Michael Dowling: A Case for Higher Level PHP Streams in PSR-7

Community News: Lead PEAR Developer Changes Focus

Andi Gutmans\' Blog: PHP is a great language!

Internet Super Hero Blog: Debugging ext/mysqli and mysqlnd


Community Events





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


version tool library composer laravel voicesoftheelephpant series community artisanfiles interview release list security introduction conference language opinion podcast symfony framework

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