You can customize how your object is represented as a string by implementing the __toString() method in your class, so when your object is type cast as a string (explicit type cast $str = (string) $myObject; or automatic echo $myObject ) , you can control the included and string format.
If you want to display only object data, the method above will work. If you want to save your object in a session or database, you need to serialize it, so PHP knows how to restore your instance.
Some code showing 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";}
Greg K Mar 18 2018-10-18T00: 00Z
source share