【问题标题】:How can I make only the parent method run in a class inheritance on PHP?如何在 PHP 的类继承中只运行父方法?
【发布时间】:2020-02-14 16:41:54
【问题描述】:

我对这个例子有一些疑问,我做了这个简单的代码,只有两个类,一个父类和一个子类。当我执行时,子必须执行父方法,父方法可以自己执行,但程序不能执行子方法。

当我运行这个程序时,同时执行父和子。有没有防止这种情况只执行父亲的方法?

class Father{

    private $element = 0; //Just to prevent recursivity

    public function add($a = null){

        if ($this->element == 0) {
            echo "<br>I'm the father"; //Execution of fhter
            $this->element = 1;

            $this->add('<br> I was an accidente'); //This instruccion call both methods, parent and soon
        }else{
            echo "<br>But not anymore"; 
        }
    }
}
class Son extends Father{
    public function add($a = null){

        parent::add();

        echo "<br>I'm the son";
        if ($a != null) {
            echo $a;
        }
    }
}

$son = new Son();
$son->add();

我有这些结果

I'm the father
But not anymore
I'm the son
I was an accident
I'm the son

如你所见,当我在父级上执行 $this->add() 方法时,它们会执行两个方法(父子的添加)。

有没有什么方法可以执行这段代码,这样当对父亲执行 $this->add() 时,它不会同时执行(父亲和儿子)?

换句话说,我期待下一个结果

I'm the father
But not anymore
I'm the son
I was an accident

顺便说一句:我不能修改父亲类。 谢谢

【问题讨论】:

  • $this-&gt;add('&lt;br&gt; I was an accidente'); 更改为self::add('&lt;br&gt; I was an accidente');。与stackoverflow.com/questions/23318045/… 类似的问题
  • 如果我不能修改Father类...我该怎么做?谢谢你的回答!!

标签: php class inheritance methods extend


【解决方案1】:

您只需将$element 添加回Son 类并像在Father 类中一样使用它:

class Son extends Father
{
    # Add this item back
    private $element = 1;

    public function add($a = null)
    {
        parent::add();
        # Check if it's set
        if($this->element == 1) {
            # Echo
            echo "<br>I'm the son";
            # Set to 0 so it doesn't recurse
            $this->element  =   0;
        }
        if ($a != null) {
            echo $a;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2012-01-06
    • 1970-01-01
    • 2023-03-27
    • 2013-07-11
    • 2012-10-23
    相关资源
    最近更新 更多