How do I disable an object that contains self-promotion?
I found this solution, but maybe there is a better one, what do you think of this?
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 class A as-is, then cancellation does not work because A has self-esteem in one of its properties.
In this case, I need to manually invoke the garbage collector.
The solution I found is to use a proxy class called AProxy which calls a special function named myDestructor in A that only destroys class A, not its parent.
Then AProxy's destructor calls myDestructor on instance A.
To make AProxy look like class A, I've overridden the __call function (you can also overload setters and getters for properties).
Do you have a better solution than this?
+3
source to share
No one has answered this question yet
Check out similar questions: