php toString not called when concatenate is used
referencing this post php 5.1.6 magic __toString method
class YourClass
{
public function __toString()
{
return $this->name;
}
}
PHP < 5.2.0
$yourObject = new YourClass();
echo $yourObject; // this works
printf("%s", $yourObject); // this does not call __toString()
echo 'Hello ' . $yourObject; // this does not call __toString()
echo 'Hello ' . $yourObject->__toString(); // this works
echo (string)$yourObject; // this does not call __toString()
what other methods am i supposed to override 开发者_C百科to get the object to display properly in the context of string concatenates/etc
currently , i am getting something like
echo 'Hello ' . $yourObject;
produces 'Hello Object ID 55';
anyone has a solution in the context of :
- client doesnt want to upgrade their php version
- not splashing __toString all over the place
?
Did you read the disclaimer in the PHP documentation?
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(). Since PHP 5.2.0, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP 5.2.0, converting objects without __toString method to string would cause E_RECOVERABLE_ERROR.
Since you're not directly involving the object with an echo (i.e. you're doing a concatenation operation first), the __toString
method won't get called. So either upgrade your version of PHP, or explicitly call __toString
.
精彩评论