我试图在扩展类中使用显示函数,该类首先在父类中获取显示函数。但是,它不会在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();
?>
答案 0 :(得分:1)
实例化保龄球类的过程实际上将通过调用父级构造函数parent::__construct();
来暗示,创建一个崭新的Cricket类以及Bowler类。
因此,尝试访问此新创建的Cricket类的属性没有任何意义。
因此,当实例化Bowler
类时,您还必须传递Cricket类成功构建所需的任何数据。
例如
<?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();