You can tailor how your object is represented as a string by implementing a __toString() method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.
If you only want to display your object’s data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.
Some code to demonstrate the difference:
class MyObject {
protected $name = ‘JJ’;
public function __toString() {
return “My name is: {$this->name}n”;
}
}
$obj = new MyObject;
echo $obj;
echo serialize($obj);
Output:
My name is: JJ
O:8:”MyObject”:1:{s:7:”*name”;s:2:”JJ”;}
Use the casting operator (string)$yourObject;