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

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 child class, which inherits from the Animal class:

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 to Animal :

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

However, this way I can not access the corPelo of the child class Cachorro , only the values of the parent class Animal .

Am I doing wrong?

    
asked by anonymous 28.12.2014 / 06:19

1 answer

3

Yes, you can, the constructor is just to initialize the class's essential properties, so each class must have its own constructor.

When a child class will initialize, it must also initialize the parent class.

To call the parent class constructor you'll use parent :

class Cachorro extends Animal {
    private $corPelo;

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

If you do not call the constructor, the initialization of class Cachorro will be capped because the initialization of the Animal class seems to be essential for Cachorro to be in order.

    
28.12.2014 / 06:31