There are three scenarios (I can think of) in which you would call a method in a subclass where the method leaves the parent class:
The method is not overwritten by a subclass; it exists only in the parent.
This is the same as your example, and generally it is better to use $this -> get_species(); . You are right that in this case the two are practically the same, but the method was inherited by a subclass, so there is no reason to differentiate. Using $this , you remain consistent between legacy methods and locally declared methods.
The method is overwritten by a subclass and has completely unique logic from the parent.
In this case, you obviously want to use $this -> get_species(); because you do not want the parent version of the method to be executed. Again, sequentially using $this , you donβt have to worry about the difference between this case and the first.
The method extends the parent class, adding to what the parent method reaches.
In this case, you still want to use `$this -> get_species(); when calling a method from other methods of the subclass. One place you call the parent method will be from the method that overrides the parent method. Example:
abstract class Animal { function get_species() { echo "I am an animal."; } } class Dog extends Animal { function __construct(){ $this->get_species(); } function get_species(){ parent::get_species(); echo "More specifically, I am a dog."; } }
The only scenario I can imagine when you would need to call the parent method directly outside the override method would be if they did two different things, and you knew that you needed the parent version of the method, not the local one. This should not be so, but if it were by itself, then an easy way to approach this is to create a new method with a name like get_parentSpecies() , where all it does is call the parent method:
function get_parentSpecies(){ parent::get_species(); }
Again, this keeps everything nice and consistent, which allows you to change / change the local method, rather than relying on the parent method.
Anthony Jun 28 2018-12-12T00: 00Z
source share