扩展类无法从父类获取数据

我试图在扩展类中使用显示函数,该类首先在父类中获取显示函数。但是,它不会在echo语句中显示变量。游戏类型(在这种情况下为“一日”)不会显示。


<?php

class Cricket

{

    protected $gameType;


    function __construct($gameType)

    {

        $this->gameType=$gameType;

    }


    function display()

    {

        echo 'The cricket match is a ' . $this->gameType . " match";

    }

}


class Bowler extends Cricket

{

    public $type;

    public $number;


    function __construct($type,$number)

    {

        $this->type=$type;

        $this->number=$number;


        parent::__construct($this->gameType);

    }


    function display()

    {

        parent:: display();

        echo " with " . $this->number . " " . $this->type . " bowler";

    }

}   


$one = new Cricket("day-night");

$one->display();


echo'<br>';


$two  = new Cricket("day-night");

$two = new Bowler("left-hand","2");

$two->display();

?>


慕码人8056858
浏览 98回答 1
1回答

茅侃侃

实际上,实例化保龄球类的过程,正如调用父级构造函数所暗示的那样parent::__construct();,将创建一个全新的板球类以及保龄球类。因此,尝试访问此新创建的Cricket类的属性没有任何意义。因此,当您实例化Bowler该类时,您还必须传递Cricket类成功构建所需的任何数据。所以举个例子<?phpclass Cricket{&nbsp; &nbsp; protected $gameType;&nbsp; &nbsp; function __construct($gameType)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->gameType=$gameType;&nbsp; &nbsp; }&nbsp; &nbsp; function display()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; echo 'The cricket match is a ' . $this->gameType . " match";&nbsp; &nbsp; }}class Bowler extends Cricket{&nbsp; &nbsp; public $type;&nbsp; &nbsp; public $number;&nbsp; &nbsp; function __construct($gameType, $type, $number)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->type=$type;&nbsp; &nbsp; &nbsp; &nbsp; $this->number=$number;&nbsp; &nbsp; &nbsp; &nbsp; parent::__construct($gameType);&nbsp; &nbsp; }&nbsp; &nbsp; function display()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent:: display();&nbsp; &nbsp; &nbsp; &nbsp; echo " with " . $this->number . " " . $this->type . " bowler";&nbsp; &nbsp; }}&nbsp; &nbsp;$two = new Bowler('day-night', "left-hand","2");$two->display();
打开App,查看更多内容
随时随地看视频慕课网APP