Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php 5.1.6 magic __toString method

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?

like image 519
nacho10f Avatar asked May 25 '10 05:05

nacho10f


2 Answers

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
like image 156
Stefan Gehrig Avatar answered Oct 10 '22 04:10

Stefan Gehrig


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.

like image 21
Weston C Avatar answered Oct 10 '22 04:10

Weston C