dongliyan7318 2013-10-12 00:45
浏览 47
已采纳

PHP子类不会覆盖新值

I am very new to OOP and trying to figure it out. I have the following code for a Mammal class which I plan to develop further. I have a child class Bear that echoes the correct values, but I can't over-write the $name, $move, $ear, or $sound values in the subclass Grizzly.

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();

The output I am trying to get is: "The grizzly bear has four claws. The offspring is birthed live and move by lumbering. They eat salmon and talk by roaring." I appreciate any help!

  • 写回答

3条回答 默认 最新

  • dongming0505 2013-10-12 01:00
    关注

    The reason is that your bear class does not seem to take variables.

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

    Here is what I did to make it work

    
    
    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

    Note: That's how I made it work

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟