Php:在错误的抽象级别调用错误的方法

时间:2012-10-28 22:34:29

标签: php oop polymorphism

这是一个代码:

abstract class A
{
    abstract public function add();

    public function callItself()
    {
        echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
        if (rand(1,100) == 5) { die; }
        $this->callItself();
    }
}

class B extends A
{
    public function add()
    {
        echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
    }
}

class C extends B
{
    public function add()
    {
        echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
        parent::add();
        parent::callItself();
    }

    public function callItself()
    {
        echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
        throw new Expection('You must not call this method');
    }
}

$a = new C();
$a->add();
die;
在课程C

,不得调用callItself(),因此会丢弃异常。我不能将它设置为私有我们知道:)但是在10行,$this->callItself();调用**C**而不是A的方法,因此它会死掉。但我不想要它,如何避开它?

1 个答案:

答案 0 :(得分:2)

使用self::callItself()代替$this->callItself();

替换

public function callItself()
{
    echo __CLASS__.':'.__FUNCTION__.' ('.__LINE__.')<br>';
    if (rand(1,100) == 5) { die; }
    $this->callItself();
}

使用

public function callItself() {
    echo __CLASS__ . ':' . __FUNCTION__ . ' (' . __LINE__ . ')<br>';
    if (rand(0, 2) == 0) { <------- Better Probability 
        die();
    }
    self::callItself(); <---- This would continue to call A:callItself until die
}

输出

C:add (23)
B:add (17)
A:callItself (7)
A:callItself (7)
A:callItself (7)
A:callItself (7)
A:callItself (7)
A:callItself (7)