Serialize an object from the inside

I have a class testClassthat has a method save. This method stores the object in the database. But before saving it is necessary to serialize the object. How can I serialize an object from a class to do this?

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.

+4
source share
1 answer

First you need to pass $thisin serialize(), not self:

$serializedObject = serialize($this);

Secondly, if you do not implement the interface Serializable(as from PHP 5.1), you need to implement a “magic method” __sleep()for serializing private or protected properties:

public function __sleep() {
    return array('prop');
}

.

+5

All Articles