Implement your own destructor in A
class. Then it will be called instead of parent destructor. Leave B
class without changes:
class Thing
{
public function __destruct()
{
echo "Destructed";
}
}
class A extends Thing
{
public function __construct()
{
echo "Class A initialized";
}
public function __destruct()
{
// Do nothing
}
}
class B extends Thing
{
public function __construct()
{
echo "Class B initialized";
}
/* Here I WANT the destructor of the Thing class */
}
Test run with:
$a = new A;
$b = new B;
outputs:
Class A initialized
Class B initialized
Destructed
Another option is checking class name in __destruct
in parent class:
class Thing
{
public function __destruct()
{
if ('A' == get_called_class()) {
echo "DestructedA" . PHP_EOL;
}
}
}
In this case you don't have to write destructors in child classes.
Update:
Simple example for storage of objects:
class ThingsStorage
{
// here we just store number of created objects
protected static $storageSize = 0;
// Add 1 when new object created
public static function increment()
{
self::$storageSize++;
}
// Substract 1 when object destructed
public static function decrement()
{
self::$storageSize--;
}
// get current size
public static function getSize()
{
return self::$storageSize;
}
}
class Thing
{
public function __destruct()
{
// object destroyed - decrement storage size
ThingsStorage::decrement();
// if no objects left - call special code
if (ThingsStorage::getSize() == 0) {
echo "Destructed" . PHP_EOL;
}
}
}
class A extends Thing
{
public function __construct()
{
echo "Class A initialized" . PHP_EOL;
// increment storage size
ThingsStorage::increment();
}
}
class B extends Thing
{
public function __construct()
{
echo "Class B initialized" . PHP_EOL;
// increment storage size
ThingsStorage::increment();
}
}