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

Extened class not able to get data from parent class

我正在尝试在我的扩展 class 中使用一个显示函数,它首先在父 class 中获取一个显示函数。但是,它不会在 echo 语句中显示变量。游戏类型(在本例中 "One-day")不显示。

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

实例化您的 Bowler class 的过程实际上将创建一个全新的 Cricket class 以及 Bowler class。

因此尝试访问这个新创建的 Cricket class 的 属性 是没有意义的。

因此,当您实例化 Bowler class 时,您还必须传递 Cricket class 成功构建所需的任何数据。

例如

<?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($gameType, $type, $number)
    {
        $this->type=$type;
        $this->number=$number;

        parent::__construct($gameType);
    }

    function display()
    {
        parent:: display();
        echo " with " . $this->number . " " . $this->type . " bowler";
    }
}   

$two = new Bowler('day-night', "left-hand","2");
$two->display();