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?