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:

<?php
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 );

echo $A;
echo \n;

echo $B;
echo \n;
?>

Outputs:

Hello World !
Hello World Hello World !

In php 5.2.1

and

Hello World !
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

$SomeObject->_toString();


Share this:
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Bumpzee
  • BlinkList

4 Responses to “PHP “__toString” magic method: not so magic before 5.2.0”

  1. donald Says:

    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 ;)

  2. mezei Says:

    I didn’t run the php file, but I think this outputs:
    Hello World (A) !
    Hello World (B) Hello World (A) !

  3. admin Says:

    You are right, my bad on that typo…

  4. Amaroq Says:

    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.

Leave a Reply