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
What would actually be pretty nice is a
__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.
