3

I have an array of Client class objects stored in a PHP array. Sometimes I need to unset() one of those objects in the array and I don't want to have to worry about explicitly closing the socket connection. I want __destruct() to do that for me.

class A{

    private $id;

    public function __construct( $id ){
        $this->id = $id;
    }

    public function __destruct(){
        echo "Calling destruct on " . $this->id . ".\n";
    }

}

$array = array();

for($i=0;$i<5;$i++){
    $array[$i] = new A($i);
}

unset($array[3]);

print_r($array);

The destructor is fired as it should for the element we're destroying. But then every other destructor in the array is called even though the elements are not being destroyed. Why?

Calling destruct on 3.
Array
(
    [0] => A Object
        (
            [id:A:private] => 0
        )

    [1] => A Object
        (
            [id:A:private] => 1
        )

    [2] => A Object
        (
            [id:A:private] => 2
        )

    [4] => A Object
        (
            [id:A:private] => 4
        )

)
Calling destruct on 0.
Calling destruct on 1.
Calling destruct on 2.
Calling destruct on 4.

Why is this happening and what alternatives do I have?

1 Answer 1

2

If $array goes out of scope, then the rest of the objects will be destroyed, too.

It looks like that is happening. You see your destruct trace message, then your print_r() output, then the rest of the objects destruct.

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

5 Comments

the destruct is being called because the script ended.. got it
That will do it, too. :) I wasn't sure if that was the end of the script or not.
yeah, but this is for a daemon.. which never ends :)
so far, it's not. and i don't think it will. why?
I misunderstood your comment about a daemon never ending to mean your code wasn't exiting. In that case, I was going to say if your daemon was forking processes to handle its tasks in parallel, then the child processes exiting would have the same effect in the output. But you aren't doing that, so nevermind. :]

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.