I’ve a class that stores an array and save its content on __destruct() event. Is __destruct() invoked automatically when there are no other reference to the object as a “whole “or relative to the current class or script that use it? Example:
class Store
{
public function set($key, $value) { $this->data[$key] = $value; }
public function __destruct() { fwrite($this->handle, serialize($this->data)); }
}
class Consumer
{
protected $store;
public function __construct() { $this->store = new Store(); }
public function __destruct() { $this->store->set('key', 'a'); }
}
// In external script...
$store = new Store();
$store->set('key', 'b');
new Consumer();
When __destruct() is called in this example? Twice? One? What is the value of key?
The consumer’s would be called first since it immediately has no reference. Then the store’s when the script exits:
This is per object. Each object that is created/destroyed will have the construct/destruct methods called.