1
I started studying PHPOO and I’m having difficulty accessing the attributes of the class Pessoa
that are private within the class Login
, follows the code
class person
class Pessoa {
private $nome;
private $idade;
public function getNome(){
return $this->nome;
}
public function setNome($n){
$this->nome = $n;
}
public function getIdade(){
return $this->idade;
}
public function setIdade($i){
$this->idade = $i;
}
public function dados_nome() {
$this->nome = "Fulano de Tal";
$this->setNome($this->nome);
//echo ''.$this->nome.' '.$this->sobrenome.' de '.$this->idade.' está online.';
}
public function dados_idade() {
$this->idade = 21;
$this->setIdade($this->idade);
}
}
class Login
class Login {
public $email;
public $pass;
public function logar() {
$this->email = "[email protected]";
$this->pass = "123456";
if ($this->email == "[email protected]" and $this->pass == "123456") :
$dados = new Pessoa;
$dados->dados_nome();
$dados->dados_idade();
echo "Bem vindo ".$dados->nome." de ".$dados->idade." anos.";
else :
echo "Dados incorretos.";
endif;
}
}
Fatal error: Uncaught Error: Cannot access private Property Pessoa::$nome in C: xampp htdocs testes class.php:47 Stack trace: #0 C: xampp htdocs testes index.php(12): Login->logar() #1 {main} thrown in C: xampp htdocs testes class.php on line 47
Private properties can only be accessed by the class itself. You cannot instantiate the class
Pessoa
and want to directly access the property$nome
where it is private, if you want to achieve this object you have two options: Change the visuality topublic
or access the methodgetNome()
. Documentation– Valdeir Psr
@Valdeirpsr Ué, I thought the
getters
andsetters
was for this, to access a private attribute outside or inside another class– goio
they are, but you’re trying to access a private object directly.
echo "Bem vindo ".$dados->nome."
and as the property is private, it is not possible. You must useecho "Bem vindo ".$dados->getNome()."
– Valdeir Psr