Travis Swicegood

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.

About

Travis Swicegood is a professional programmer and owner of Domain51, a web development company with a focus on non-profits, NGOs, and online activists. He doesn't change the world, he supports those who do.

He has personal a focus on web applications, performance, and stability; is author of Pragmatic Version Control using Git; and working on his second book. He has been using PHP; since '99 and still remembers how revolutionary PHP 4 was, but can't remember why. He's a TDD, open-source, and open government advocate—sometimes called a zealot—and lurker on many an open-source project mailing list when not learning other programming; languages; for fun, exploring his surroundings on bike, or tasting his latest kitchen and home-brew creations.

Contact
Around the Internet