PHP Magic Method __toString


PHP Magic Method __toString

The __toString magic method contains the usual double underscore in its front. It does does as its name implies since it strips object characteristics. The next PHP OOP examples should help you understand the details.

Integer Parameter

With the first code block, an integer is passed into the class via the constructor. As you can see, it is an integer before, during and after it leaves the class. But, it is no longer an object and the tests below indicate that.

<?php

class TestClass
{
    public $my_string;

    public function __construct($my_string)
    {
	    echo gettype($my_string)."<br/>";
        $this->my_string = $my_string;
		echo $this->my_string."<br/>";
    }

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

$my_array = array('test');
$class = new TestClass(58);
echo $class->my_string;
echo "<br/><br/>";
if (is_object($class->my_string)){
echo "Yes";
}
echo "<br/><br/>";
if ($class->my_string instanceof TestClass) {
   echo "Instance";
}
echo "<br/><br/>";
var_dump($class->my_string);
echo "<br/><br/>";
var_dump((string)$class->my_string);

?>


Browser Output

integer
58
58

int(58)

string(2) "58"

String Parameter

With this example, you can see that if we use the $class->my_string it is a string without any record of its class. But, if you analyze the variable $class, you wil see that it still maintains it association to the class; even though it is a string called my_string with a value of "test".

<?php

class TestClass
{
    public $my_string;

    public function __construct($my_string)
    {
	    echo gettype($my_string)."<br/>";
        $this->my_string = $my_string;
		echo $this->my_string."<br/>";
    }

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

$class = new TestClass('test');
echo $class;
echo "<br/><br/>";
var_dump($class);
echo "<br/><br/>";
echo var_dump($class->my_string);
echo "<br/><br/>";

if (is_object($class)){
echo "Yes";
}
echo "<br/><br/>";
if ($class instanceof TestClass) {
   echo "Instance";
}

echo "<br/><br/>";
var_dump((string)$class);
$success = settype($class, 'string');
echo (string)$class;
echo "<br/><br/>";
if (!is_object($class)){
echo "No";
}
echo "<br/><br/>";
if (!$class instanceof TestClass) {
   echo "No longer an instance";
}
?>


Browser Output

string
test
test

object(TestClass)#1 (1) { ["my_string"]=> string(4) "test" }

string(4) "test"

Yes

Instance

string(4) "test" test

No

No longer an instance