【问题标题】:Inheritance PHP, passing methods and using children's properties instead of parent's ones继承 PHP,传递方法和使用子属性而不是父属性
【发布时间】:2013-11-16 18:23:57
【问题描述】:

为什么传递给Professeur的父方法getHC()引用父(Enseignant)的$this->quota而不是子的$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);
}

我需要 $this->nbHeures - $this->quota 传递给 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;
        }
}

并使用教授的配额,而不是 Enseignant 的配额。

【问题讨论】:

  • $e = new Professeur("Charles", 292);回声 $e->getHC();应该给我 100 而不是 292...

标签: php oop inheritance methods


【解决方案1】:

我可以看到您的示例代码存在两个问题:

  1. 您的 Professeur 类没有扩展 Enseignant 类。我不确定这是否只是您在示例代码中复制的错字 - 但第二类应声明为:

    class Professeur extends Enseignant {
    
  2. $quota 成员变量在父类中被声明为私有。这意味着子类无法访问该值,而子类中的setQuota() 函数正在子类上设置一个新的(未声明的)同名变量。

    要解决此问题,您应该将$quota 变量声明为protected 而不是private

    protected $quota;
    

以下代码应该更符合您的预期:

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

另一种解决方案是将$quota 变量保留为私有变量,并使setQuota() 方法成为父类的一部分——仍然从子构造函数中调用它。

【讨论】:

  • 修复了它,它被扩展了。正在查找 $quota。
  • 那么我该如何使用正确的 $quota?我将其更改为受保护的,但它不起作用。
  • 我已经更新了您的示例,改写为我认为您正在寻找的内容。这有帮助吗?
  • 可爱又详细。 +1!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2014-02-03
  • 2021-05-07
  • 2011-11-10
  • 2012-05-03
  • 1970-01-01
相关资源
最近更新 更多