Php 5.1.6 magic __toString method

In codeigniter, Im trying to use this plugin, which requires me to implement the toString method in my models. My toString method just does

public function __toString()
{
    return (string)$this->name;
}

On my local machine with php 5.3 everything works fine, but on the production server with php 5.1.6 it shows "Object id # 48" where the value of the name property of this object should be displayed ..... I have something about the problem here , but I still don’t understand ... How can I fix this?

+5
source share
5 answers

PHP update

, , php >= 5.2.0

( ), , .

+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
+7

:

, PHP 5.2.0 __toString , echo() print(). PHP 5.2.0, (, printf() % s ), (, % d). PHP 5.2.0, __toString E_RECOVERABLE_ERROR.

, __toString , PHP < 5.2, .

+3

php magic __toString() < 5.2. , :

    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 function is automatically called

0
source

You need to install. You need to sudo apt install php7.0-mbstring change the version of PHP to suit yours.

And after that, do not forget to run service apache2 restart

Hope this helps.

0
source

All Articles