What is toString() method ?

To avoid an error if a script attempts to output MyClass as a string, another magic method is used called__toString().

Without__toString(), attempting to output the object as a string results in a fatal error. Attempt to use echo to output the object without a magic method in place:

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}

// Create a new object
$obj = new MyClass;

// Output the object as a string
echo $obj;

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "End of file.<br />";

?>
This results in the following:

The class "MyClass" was initiated!

Catchable fatal error: Object of class MyClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 40
To avoid this error, add a__toString() method:

File name : index.php

<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}


// Create a new object
$obj = new MyClass;
// Output the object as a string
echo $obj;
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "End of file.<br />";
?>
In this case, attempting to convert the object to a string results in a call to thegetProperty() method. Load the test script in your browser to see the result:

The class "MyClass" was initiated!
Using the toString method: I'm a class property!
The class "MyClass" was destroyed.
End of file.





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here