PHP “__toString” magic method: not so magic before 5.2.0
I was confident that using one of php5’s magic methods, __toString() would just work, but the fact is that the following code works in php version 5.2.1 but not in 5.1.6:
You can try this for yourself:
class ToStringTest {
protected $content;
public function __construct($content) {
$this->content = $content;
}
public function add($content) {
$this->content .= ‘ ‘ . $content;
}
public function __toString() {
return $this->content;
}
}
$A = new ToStringTest(‘Hello World (A)’);
$B = new ToStringTest(‘Hello World (B)’);
$A->add(‘!’);
$B->add( $A );
Outputs:
Hello World Hello World !
In php 5.2.1
and
Hello World Object id #1
In php 5.1.6
And then it hit me:
It is worth noting that before PHP 5.2.0 the __toString method was only called when it was directly combined with echo() or print().
Small piece of advise: always be sure to know what is a certain function’s behavior in the possible php versions your code will be running, or risk bad surprises.
Meanwhile… use







June 13th, 2007 at 12:01 pm
Nice one!
Normally I try to avoid magic functions (because I don’t believe in magic), but I thought the __toString() would be useful. I was having the same problem that you are describing here. (did a google search and found your blog).
Seems I need to update my php version on my home dev machine. Thanks for the info
November 4th, 2007 at 7:35 pm
I didn’t run the php file, but I think this outputs:
Hello World (A) !
Hello World (B) Hello World (A) !
November 6th, 2007 at 5:05 pm
You are right, my bad on that typo…
March 21st, 2008 at 4:20 pm
I came across this same problem. I made an image gallery with thumbnail generation and caching, and thoroughly tested it on my personal apache with PHP 5.2.3. Uploaded it to a friend’s webspace on her college’s server, then had to go visit some family for a week. I come back and find out that instead of displaying thumbnails that link to fullviews, it’s displaying object IDs linking to their respective fullviews. I replaced all instances of $obj that were in echoes or in other strings with $obj->__toString(), and everything worked perfect.
Had I read this sooner, I would’ve known I didn’t need to alter the actual echoes. Just the other strings.
January 16th, 2009 at 1:44 am
Just be use you’re using the right types in the right places, in ALL code you write.
Typcasting should work here and is the right thing to do, change:
$B->add( $A );
to
$B->add( (string) $A );
If php was a typed language and you could define add() like this:
public function add(string $content)
then you would not need to explicitly cast objects as above.
relying on the php team of developers to get things right first time always leads to issues so make your code as exact as possible.