PHP - Getting __sleep to return all properties of an object
If you write a custom __sleep() magic method for a PHP class, you are expected to make the method return a list of the class properties’ names that the serializer should serialize.
This is handy to reduce the amount of data stored in big objects.
But, what happens if you just want a quick way to return all the properties without having to remember to add them individually each time you modify the class? (I.e To keep the __sleep() method in synch with the class during development).
Well you don’t have to delve too deeply into introspection of an object for getting the names of all its properties. And, you don’t have to mess about making function to convert a ‘php object as array’.
TuxRadar has a nice post that provides the answer:
Its simple.
Apparently you just use the get_object_vars() wrapped up in an array_keys() function.
class MySleepyObject {
public function __sleep() {
//prepare for snoozing
return array_keys(get_object_vars($this));
}
}
