Jeśli jesteś właścicielem tej strony, możesz wyłączyć reklamę poniżej zmieniając pakiet na PRO lub VIP w panelu naszego hostingu już od 4zł!

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

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
Source: http://www.phpdeveloper.org/news/20041

<!–
var d = new Date();
r = escape(d.getTime()*Math.random());
document.writeln('’);
//–>

Posted Sierpień 29th, 2013 in WEB and PHP Development.

Leave a response: