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 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常