TravisSwicegood.com

25 September

Funny __toString() behavior

So here's another behavior in PHP that's not quite what I expected, but not all that surprising.

<?php

class SomeClass {
  public function __toString() {
    return "hello!";
  }
}

class SomeOtherClass {
  public function __toString() {
    return new SomeClass();
  }
}

echo new SomeOtherClass();
?>

Now, doesn't it seem that the echo should carry through to SomeClass::__toString()? You'd think; but you get a fatal error instead. It the "fix" isn't difficult:

class SomeOtherClass {
  public function __toString() {
    return (string)new SomeClass();
  }

And from a performance standpoint, it is better to require a string be returned than try to guess. Seemed odd, though, given PHP's loose typing.

3 comments

Nice to see that other people stumble across the same problems. See http://www.stubbles.org/archives/27-Return-type-hints.html. ;)
Hey Frank - I already know __toString() forced a string, what I found odd was that it wasn't intelligent enough to realize the object returned could be a string.

What would actually be pretty nice is a __toScalar() code. The (scalar)$object would just convert the object into whatever its primitive type is. Of course, I'd also be in favor of adding __toInt(), __toBool(), and __toFloat() too. :-)
Haha I tried to do the exact same thing about a week ago and I thought "Why oh why is '1' == 1 and this won't work?" Nice to see we share similar frustrations.

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)