Reputation: 105547
I have the class testClass
which has the method save
. This method saves object to a database. But it needs to serialize object before saving. How can I serialize object from within the class to do that?
class testClass {
private $prop = 777;
public function save() {
$serializedObject = serialize(self);
DB::insert('objects', array('id', 'object'))
->values(array(1, $serializedObject))
->execute();
}
}
serialize(self) obviously doesn't work.
Upvotes: 4
Views: 1234
Reputation: 158210
First, you need to pass $this
to serialize()
rather than self
:
$serializedObject = serialize($this);
Secondly, unless you are not implementing the Serializable
interface (as from PHP 5.1 ) you need to implement the "magic method" __sleep()
in order to serialize private or protected properties:
public function __sleep() {
return array('prop');
}
This manual page about serializing objects should help further.
Upvotes: 5