Pobe
Pobe

Reputation: 2793

Inheritance PHP, passing methods and using children's properties instead of parent's ones

Why does parent's method getHC() passed to Professeur refers to $this->quota of parent (Enseignant) instead of children's $this->quota.

abstract class Enseignant {

  private $quota; //empty

  public function __construct($nom, $nbHeures)[...]

  public function getHC(){
     return $this->nbHeures - $this->quota; //Ici le problème
  }

  abstract protected function setQuota($q);
}

I need $this->nbHeures - $this->quota to be pass to Professeur

class Professeur extends Enseignant {
        const QUOTA = 192;

        public function __construct($nom, $nbHeures) {
            parent::__construct($nom, $nbHeures);
            $this->setQuota(self::QUOTA);
        }

        protected function setQuota($q) {
            $this->quota = $q;
        }
}

And use Professeur's quota and not Enseignant's one.

Upvotes: 1

Views: 135

Answers (1)

jcsanyi
jcsanyi

Reputation: 8174

I can see two problems with your sample code:

  1. Your Professeur class does not extend the Enseignant class. I'm not sure if this is just a typo as you copied in your sample code - but the second class should be declared as:

    class Professeur extends Enseignant {
    
  2. The $quota member variable is declared as private in the parent class. This means that the child class cannot access the value and the setQuota() function in the child class is instead setting a new (undeclared) variable with the same name on the child class.

    To fix this, you should declare the $quota variable as protected instead of private.

    protected $quota;
    

The following code should work more like what you're expecting:

abstract class Enseignant {
    protected $quota; // declare as protected so it can be
                      // accessed and modified from the child class

    public function __construct($nom, $nbHeures) {
        $this->nbHeures = $nbHeures;
    }

    public function getHC() {
        return $this->nbHeures - $this->quota;
    }

    abstract protected function setQuota($q);
}

class Professeur extends Enseignant {
    const QUOTA = 192;

    public function __construct($nom, $nbHeures) {
        parent::__construct($nom, $nbHeures);
        $this->setQuota(self::QUOTA);
    }

    protected function setQuota($q) {
        $this->quota = $q;
    }
}

$e = new Professeur("Charles", 292);
echo $e->getHC(); // returns 100 now

An alternate solution would be to leave the $quota variable as private, and make the setQuota() method part of the parent class - still calling it from the child constructor.

Upvotes: 3

Related Questions