1

这是一个代码:

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;

在类CcallItself()不能调用,所以它会抛出一个异常。正如我们所知,我不能将其设置为私有 :) 但是在第 10 行,$this->callItself();调用该方法**C**而不是A所以它死了。但我不想要它,如何躲避它?

4

1 回答 1

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)
于 2012-10-28T22:45:47.797 回答