4
When developing a simple PHP POO application, I came across an unexpected error, and I have no idea why. I’m starting now to study object-oriented programming and only have a small C-base#.
The program itself is simple: two classes (Pessoa
and Funcionario
) being Funcionario
inherited from the class Pessoa
, each with 2 methods, ler()
and mostrarDados()
.
My goal is simple to create an object and pass by reference all information to the method lerDados()
class Funcionario
, and within this, call the method LerDados()
class Pessoa
(parent::lerDados()
) passing only relevant class information (nome
, idade
and sexo
), the others is "read" in the class itself Funcionario
(empresa
and salario
).
Error: Declaration of Funcionario::lerDados($stringNome, $stringIdade, $stringSexo, $stringEmpresa, $stringSalario) should be compatible with Pessoa::lerDados($stringNome, $stringIdade, $stringSexo) in C:\wamp64\www\POO\namespace1.php on line 31
<?php
class Pessoa{
// PROPRIEDADES
protected $nome;
protected $idade;
protected $sexo;
// METODOS
public function lerDados($stringNome, $stringIdade, $stringSexo){
$this->nome = $stringNome;
$this->idade = $stringIdade;
$this->sexo = $stringSexo;
}
public function mostrarDados(){
return "Nome: ".$this->nome."<br>\nIdade:".$this->idade."
<br>\nSexo:".$this->sexo;
}
}
class Funcionario extends Pessoa{
// PROPRIEDADES
protected $empresa;
protected $salario;
// METODOS
public function lerDados($stringNome, $stringIdade, $stringSexo,
$stringEmpresa, $stringSalario){
$this->nome = $stringNome;
$this->idade = $stringIdade;
$this->sexo = $stringSexo;
parent:: lerDados($this->nome,$this->idade,$this->sexo); // CHAMAR METODO DAS CLASSE PAI
$this->empresa = $stringEmpresa;
$this->salario = $stringSalario;
}
//public function mostrarDados(){}
} // <------ERRO NESTA LINHA <-------
$vendedor = new Funcionario();
$vendedor->lerDados("Yuri", "19", "Masculino", "Tam", "3000");
?>
Is it me who is seriously wrong, or does PHP not accept this kind of polymorphism? Could someone guide me on how to fix this, and answer why this brutally fatal mistake happened?
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero