Search code examples
phpclassinheritancemethodsextend

How can I make only the parent method run in a class inheritance on PHP?


I have some inquiries aboute this example, I make this simple code, just two classses, a parent and son class. When I execute the son must execute the parent and the parent method can execute himself BUT the program must not execute the son method.

When I run this program, execute both, parent and son. Exist any to prevent this and execute only the father's method?

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

And I have these results

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

Like you see, when I execute the $this->add() method on parent, they execute both methods (add of father and son).

Is there any way to perform this code so that when executing $this->add() on the father, it does not execute both (the father and the son)?

In other words, I was expecting the next result

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

BY THE WAY: I cant modify the Father class. Thanks


Solution

  • You just need to add the $element back into the Son class and use it like you did in the Father class:

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