4
When rewriting a method, in PHP, I can use a variable to receive the method?
I did the example below and it worked normally, but I don’t know if this is correct or if it is the best way to rewrite a parent-class method.
abstract class Animal{
...
public function dadosAnimal(){
$dados = " Nome: ". $this->nome;
$dados .= "Idade: ". $this->idade;
return $dados;
}
class Cachorro extends Animal(){
...
public function dadosAnimal(){
//Posso fazer ou vai contra algum principio ou patter ?
$dados = parent:: dadosAnimal();
$dados .= " Cor do pelo: ". $this->corPelo;
return $dados;
}
What I want is not to have to keep repeating the same father class code in the daughter classes and also have the benefit of changing something only in the parent class and the change is reflected for all the daughter classes that use the parent class method.
Prevent this:
public function dadosAnimal(){
parent::dadosAnimal();
//Copiar o método inteiro da classe-pai
$dados = "<br/> Nome: ". $this->nome;
$dados .= "<br/> Idade: ". $this->idade;
//reescrever, adicionando isso
$dados .= "<br/> Cor do pêlo: ". $this->corPelo;
return $dados;
what I want to have as benefit is just that, to be able to change something in the parent class method and to reflect it to what is using the method, without it being necessary to change that is "inheriting".
– Leandro Macedo
In this case, you’re doing it the right way. I’m sorry if it wasn’t clear in the answer.
– Vinícius Gobbo A. de Oliveira