4

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

What if my object testClass included objects of other classes as properties, should those other classes implement __sleep function as well for private properties?
@Maximus Yes, they have to. If not, you need to use __sleep() and __wakeup of testClass to get necessary data to serialize and unserialize them again.
@Maximus No, __sleep and __wakeup have to be public
@Maximus Also check the Serializable interface. (I forgot to mention this)
__sleep() / __wakeup() do not behave different than other methods. You may define the base behaviour in the parent class and refine it in sub classes
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.