[php] multiple ways of calling parent method in php

At first I was confused why both of the method calls in the constructor work, but now I think I understand. The extending classes inherit the parent's methods as if they were declared in the class itself, AND the methods exist in the parent, so both should work.

Now I'm wondering if there is a preferred way (i.e. best practice) of calling the method (via parent or this), and whether or not these are truly identical ways of executing the same code, or if there are any caveats when using one over the other.

Sorry, I'm probably over thinking this.

abstract class Animal {

    function get_species() {

        echo "test";

    }

}

class Dog extends Animal {

    function __construct(){

        $this->get_species();
        parent::get_species();

    }

}

$spike = new Dog;

This question is related to php

The answer is


Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.