2012年2月9日星期四

Refulz.com: The __toString() Method - Objects as Strings


On the Refulz.com blog there's a recent post introducing the __toString() magic method in PHP. This handy method allows you to define how to return an object when it's referenced as a string.



We started the study of PHP magic methods by learning about __get() magic method. [...] PHP is loosely typed language and same variable can be used or referred as string, number or object. The __toString() method is called when the code attempts to treat an object like a string. This function does not accept any arguments and should return a string.


Some quick code is included showing how it works - returning a combined string made from two private class properties when the object ($obj) is echoed out. They also show multiple ways of using the method in both pre- and post-PHP 5.2.

没有评论:

发表评论