multiple ways of calling parent method in php

前端 未结 2 1157
无人及你
无人及你 2020-12-12 18:43

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 we

2条回答
  •  难免孤独
    2020-12-12 19:19

    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.

提交回复
热议问题