Search code examples
phpoopserializationserializable

__destruct method is called correctly when implementing Serializable interface in php?


I am learning to Serializable interface.

php.net stated that

This does not invoke __destruct() or have any other side effect unless programmed inside the method.

which i would like to separate in two parts according to my sense as:

1): __destruct() is not called when implementing the Serializable interface. But when i use __destructor() method as:

class myClass implements Serializable{

    public function serialize(){
        return 'I am serialized';
    }

    public function unserialize($serialized){
        //--
    }

    public function __destruct(){
        echo "Hello world";
    }
}

$obj = new myClass();

The __destructor method works fine and this simply output the following:

Hello world

2): If you need to use __destruct() method you need to declare inside the method. But when i declare inside the method as:

class myClass implements Serializable{

    public function serialize(){
        return 'I am serialized';
    }

    public function cutomDest(){

        public function __destruct(){
            echo "Hello world";
        }

    }

    public function unserialize($serialized){
        //--
    }
}

$obj = new myClass();

It return the following parser error as:

Parse error: syntax error, unexpected 'public' (T_PUBLIC) in .....

Why php.net provides wrong documentation or may be i am wrong. Please can anyone teach me about the documentation of __constructor() and __destructor() in the concept of Serializable interface on the following reference page ?

Reference Link http://php.net/manual/en/class.serializable.php.


Solution

  • Implementing the Serializable interface has nothing to do with the __destruct() method. The serialize() method is used to save the object as a string, which can be saved in a file (like the session system do). This step does not trigger the __destruct() method since the object still exists and there is most likely a variable reference to that object.

    In your first case, the __destruct() method is not called by any serialization step. In fact, you don't even serialize your object. However your destructor is called because your script ended and all objects are going to be deleted.

    In your second case, you cannot declare methods inside methods, you get the error message in your question. When you are in your serialize() method you can call __destruct() if you want... or don't. But in regards to the Serializable interface the __destruct() method is irrelevant.