Can I declare a builder in the child classes when the mother class is abstract and already has a builder?

Asked

Viewed 2,607 times

3

My question is this: If I can declare a constructor in a class abstract and also in the child classes. And also how to access their values. For example:

abstract class Animal {
    private $nome;
    private $idade;

    public funtion __construct($nome, $idade) {
        $this->nome = $nome;
        $this->idade = $idade;
    }
}

And in the daughter class, who inherits from the class Animal:

class Cachorro extends Animal {
    private $corPelo;

    public function __construct($corPelo) {
        $this->corPelo = $corPelo;
    }
}

And when I try to instantiate I call the class Cachorro instantiating the values for Animal:

$dog = new Cachorro('belinha', 4, 'preto');

But that way I can’t access corPelo daughter-class Cachorro, only the values of the mother class Animal.

I’m doing it wrong?

  • Have you removed the '' of the $dog = new Dog ('Little Bee',4,'black')? It would be 'Little Bee' and not 'Little Bee'. Or I’m wrong?

  • I typed wrong the code here in stackoverflow. But even though it’s like this 'Belinha' (between quotes) does not work :/

  • but in case I use a daughter-class to inherit the abstract mother class, it might ?

  • then I urge the child class and access the attributes of the abstract mother class

  • Forget it, I removed the comment. I saw the instance of the wrong class.

1 answer

3


Yes, it can, the constructor is precisely to initialize essential class properties, so each class must have its own constructor.

When a daughter class will initialize, she also needs to initialize the parent class.

To call the parent class builder you will use the parent:

class Cachorro extends Animal {
    private $corPelo;

    public function __construct($nome, $idade, $corPelo) {
        parent::__construct($nome, $idade);
        $this->corPelo = $corPelo;
    }
}

I put in the Github for future reference.

If you do not call the constructor to initialize the class Cachorro will be bad since the class initialization will be missing Animal which seems to me to be essential to the Cachorro be in order.

  • our perfect, worked out here. Muitooo thanks :)

  • I can use Parent in child classes to change/add any parent method property or have some restriction ?

  • 2

    Properties are those that are there, you cannot add or remove properties from another class. At least not under normal conditions (PHP accepts doing crazy things). But if you want to know if you can access properties of the upper class, you can as long as its visibility is protected. Or public but then everyone can. With private can’t.

  • ok, so Parent is only used for the constructor ?

  • 1

    No, you can always use any member to access the inherited upper class.

  • Splendid......

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.