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:
// 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:
// 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.
Trending Tutorials