OOPs Tutorials
- What is OOPs
- Access Modifier
- Constructor
- Destructor
- Polymorphism
- Inheritence
- Method Overriding
- Abstract class
- Interface
- Traits
- This keyword
- static keyword
- Final keyword
- Class Constant
- Exception Handling
- Binding in php
- tostring in php
- Object Iteration
- Reflection
- Magic methods
- Namespaces
- CRUD Function
- OOPs CRUD
- CRUD Example
Important Links
What is toString?
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.