How to access attributes of the parent class in PHP?

1

How do I access the attributes of the parent class once I instantiated the child?

Direct access $Filho->atributoPai does not work.

Access by function $Filho->getterPai does not work.

For each inherited child should I get getters attributes from your parent?

<?php

    class Pessoa {
        function __construct($nome, $sexo, $idade) {
            $this->nome = $nome;
            $this->sexo = $sexo;
            $this->idade = $idade;
        }
        function getNome() {
            return $this->nome;
        }
        private $nome;
        private $sexo;
        private $idade;
    }
    class Amigo extends Pessoa {
        function __construct($nome, $sexo, $idade, $diaDoAniversario) {
            parent::__construct($nome, $sexo, $idade);
            $this->diaDoAniversario = $diaDoAniversario;
        }
        private $diaDoAniversario;
    }

    $joao = new Amigo("Jonis", "masc", 20, 30);
    echo "Nome: $joao->nome";  // Notice: Undefined property: Amigo::$nome
    echo "Nome: $joao->getNome()"; // Undefined property: Amigo::$getNome

?>
    
asked by anonymous 06.05.2018 / 22:30

1 answer

1

One of the problems is that you can not force a complex expression inside a string , you have to do concatenation, or with braces.

Also if you want to access the field ( I do not call the attribute because it has no documentation that says this in any mainstream language which is concerned with defining things correctly) then you need to make it public, otherwise you can not access it in the top-class object.

To tell you the truth I do not know if I should do this in PHP. Script languages are not suitable for complex systems. It's like using OOP in micro-services, if the services are really micro, and one of the reasons for doing this is to make the code not have complexity, so OOP is unnecessary, which is a style to organize complexity. But in general people are adopting things without thinking about what they are doing and why they adopted it.

Incidentally, the upper class should not be instantiated, so it should be abstract .

class Pessoa {
    function __construct($nome, $sexo, $idade) {
        $this->nome = $nome;
        $this->sexo = $sexo;
        $this->idade = $idade;
    }
    function getNome() {
        return $this->nome;
    }
    public $nome;
    private $sexo;
    private $idade;
}
class Amigo extends Pessoa {
    function __construct($nome, $sexo, $idade, $diaDoAniversario) {
        parent::__construct($nome, $sexo, $idade);
        $this->diaDoAniversario = $diaDoAniversario;
    }
    private $diaDoAniversario;
}

$joao = new Amigo("Jonis", "masc", 20, 30);
echo "Nome: {$joao->nome}";
echo "Nome: " . $joao->getNome();
    
06.05.2018 / 22:54