PHP 子类不会覆盖新值

标签 php oop

我是 OOP 的新手,正在努力弄明白。我有以下哺乳动物类代码,我计划进一步开发。我有一个反射(reflect)正确值的子类 Bear,但我不能在子类 Grizzly 中重写 $name、$move、$ear 或 $sound 值。

abstract class Mammal
{
    protected $name;
    protected $limbs;
    protected $offspring = 'live';
    protected $move;
    protected $eat;
    protected $sound;

    protected function __construct($name, $limbs, $offspring, $move, $eat, $sound) {
        $this->name = $name;
        $this->limbs = $limbs;
        $this->offspring = $offspring;
        $this->move = $move;
        $this->eat = $eat;
        $this->sound = $sound;
    }

    public function getOutput() {
        echo "The {$this->name} has four {$this->limbs}. The offspring is birthed {$this->offspring} and move by {$this->move}. They eat {$this->eat} and talk by {$this->sound}.";
    }
}

class Bear extends Mammal
{
    public function __construct() {
        Mammal::__construct('bear', 'claws', $this->offspring, '', '', '');
    }
}

class Grizzly extends Bear
{
    public function __construct() {
        Bear::__construct('grizzly bear', 'claws', $this->offspring, 'lumbering', 'salmon', 'roaring');
    }
}

$grizzly = new Grizzly;
$grizzly->getOutput();

我想要得到的输出是:“灰熊有四只爪子。后代是活生生的,靠笨拙移动。它们吃鲑鱼,靠吼叫说话。”感谢您的帮助!

最佳答案

原因是你的熊类似乎没有带变量。


class Bear extends Mammal
{
    public function __construct() { //See, this constructor takes nothing
        Mammal::__construct('bear', 'claws', $this->offspring, '', '', '');
    }
}

下面是我做的事情



class Bear extends Mammal
{
    public function __construct($bear = 'bear') {//right hear
        Mammal::__construct($bear, 'claws', $this->offspring, '', '', '');
    }
}

Your code in codepad.org with my little change

注意:我就是这样实现的

关于PHP 子类不会覆盖新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329247/

相关文章:

php - Slim Framework 3. 如何设置$baseURL供所有 View 使用?

php - 将 MySQL 行导入表中

language-agnostic - 我应该使用像 IEnumerable 这样的接口(interface),还是像 List<> 这样的具体类

php - OOPHP - 如何从数据库行数组创建多个对象?

c++ - 是否有嵌套类的用例?

java - 计算字符串中空格的递归方法如何工作?

php - 压缩主文件夹,里面有子文件夹

php - mysql_real_escape_string 和 strip_slashes 问题

php - PHP 的 VSCode 类方法提示

c++ - 我怎么知道临时对象何时被创建和销毁?