In codeigniter Im trying to use this plugin which requires I implement a toString method in my models. My toString method simply does
public function __toString()
{
return (string)$this->name;
}
On my local machine with php 5.3 everything works just fine but on the production server with php 5.1.6 it shows "Object id#48" where the value of the name property of that object should appear..... I found something about the problem here but I still dont understand... How can I fix this?
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()
PHP >= 5.2.0
$yourObject = new YourClass();
echo $yourObject; // this works
printf("%s", $yourObject); // this works
echo 'Hello ' . $yourObject; // this works
echo 'Hello ' . $yourObject->__toString(); // this works
echo (string)$yourObject; // this works
To quote from the manual:
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.
I think you have call the __toString method manually if you're using it in PHP < 5.2 and not in the context of an echo or print.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With