I have found this solution, but perhaps there is a better one, what do you think about it?
class A
{
#A self-reference
private $_a;
#Construcotr makes a self-reference
public function __construct()
{
$this->_a = $this;
}
#Some other functions
public function hello()
{
echo 'Hello, world!' . PHP_EOL;
}
#Function to destruct just this object, not its parent
public function myDestruct()
{
unset($this->_a);
var_dump($this);
}
}
class AProxy
{
#The proxied object
public $_a;
#The constructor has to be rewritten
public function __construct()
{
$this->_a = new A();
}
#The destructor
public function __destruct()
{
$this->_a->myDestruct();
unset($this->_a);
var_dump($this);
}
#Some other functions
public function __call($fct, $args)
{
call_user_func(array($this->_a, $fct), $args);
}
}
echo 'START' . PHP_EOL;
#Use class AProxy instead of class A
$a = new AProxy();
$a->hello();
unset($a);
#Otherwize you need to trigger the garbage collector yourself
echo 'COLLECT' . PHP_EOL;
gc_collect_cycles();
echo 'END' . PHP_EOL;
If I use the class A as-is, then unsetting doesn't work because A has a self-reference in one of its property.
In this case I need to manually call the garbage collector.
The solution I have found is to use a proxy class, called AProxy, which calls a special function named myDestructor in A which only destruct the A class and not its parent.
Then the destructor of AProxy calls myDestructor on the instance of A.
In order to make AProxy resemble the A class, I reimplemented the __call function (the setters and getters for properties may also be overloaded).
Do you have a better solution than that?