在最后一堂课中只破坏一次。 PHP

时间:2016-10-16 09:16:08

标签: php

我想在PHP中只使用一次destruct函数。我希望它在扩展父类的最后一个类的末尾。像这样:

class Thing
{
    public function __destruct()
    {
        echo "Destructed";
    }
}

class A extends Thing
{
    public function __construct()
    {
        echo "Class A initialized";
    }

    /* Here I DON'T WANT the destructor of the Thing class */
}

class B extends Thing
{
    public function __construct()
    {
        echo "Class B initialized";
    }

    /* Here I WANT the destructor of the Thing class */
}

1 个答案:

答案 0 :(得分:1)

A类中实现自己的析构函数。然后它将被调用而不是父析构函数。保留B课程而不做任何更改:

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 */
}

试运行:

$a = new A;
$b = new B;

输出:

Class A initialized
Class B initialized
Destructed

另一个选项是检查父类__destruct中的类名:

class Thing
{
    public function __destruct()
    {
        if ('A' == get_called_class()) {
            echo "DestructedA" . PHP_EOL;
        }

    }
}

在这种情况下,您不必在子类中编写析构函数。

<强>更新

存储对象的简单示例:

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();
    }
}