php 5.1.6 magic __toString method

2019-06-22 17:35发布

问题:

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?

回答1:

Upgrade PHP

I'm dealing with the same problem, I suspect your best option will be to upgrade php on the production server to >= 5.2.0

In the future (I'm currently learning this the hard way), try to develop on the same version you will deploy to.



回答2:

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


回答3:

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.



回答4:

You have to explicitly call the php magic function __toString() for versions < 5.2. So your code will become something like this:

    public function myname()
    {
       $name = $this->name;
       return $name.__toString(); //for php versions < 5.2,will also work > 5.2
    }

For versions > 5.2 the __toString is automatically called



回答5:

You need to install sudo apt install php7.0-mbstring Need to change the PHP version as per your.

And after this do not forget to run service apache2 restart

Hope this will help.