原文
http://www.jcinacio.com/2007/04/ ... o-magic-before-520/
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();