PHP 5 and the magic __toString() method

Working with PHP 5 I thought the ‘magic’ method __toString would be a really great way of substituting objects for simple data types. That seemed the whole point of good object oriented design, so I could change the way a piece of data worked without having to track down every call to it and change that. Unfortunately, it seems that __toString() is only called if used directly from an echo or print statement. Now: what is the point of that, really?

I can see that we don’t want it called by default everywhere, otherwise there would never be a way to grab a reference to an object. But surely there are a large number of ‘string only’ functions that could invoke it? If I set up an object called $parameter with a method of __toString() and call it in code with echo “This is the value: ” . $parameter then there really can’t be much else I’m doing with it than using it as a string. If the toString() method isn’t called then, why do we have it at all?

It seems that this may be another case where PHP’s lack of strong typing is severely limiting it’s future development as a robust object oriented language and the __toString() implementation smacks of a half-implemented hack to me.

PHP 5 magic __toString() method on the Zend site

Advertisements
This entry was posted in PHP, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s